Several methods of JS object-oriented 2

Source: Internet
Author: User

Define the Circle class, member function area () with member variable r, constant pi, and calculated areas

1. Factory mode

var Circle = function () {   var obj = new Object ();   Obj. PI = 3.14159;      Obj.area = function (r) {       return this. PI * R * r;   }   return obj;} var c = new Circle (); Alert (C.area (1.0));

2. More formal wording

function Circle (r) {      THIS.R = r;} Circle.pi = 3.14159; Circle.prototype.area = function () {  return circle.pi * THIS.R * THIS.R;} var c = new Circle (1.0);   

3.json notation

var circle={   ' PI ': 3.14159, ' area ': function (r) {          return this. PI * R * r;        }; Alert (Circle.area (1.0));

4. A little change, but essentially the same as the first

var circle=function (r) {        this.r=r;} Circle.pi = 3.14159; circle.prototype={    area:function () {        return this.r*this.r*circle.pi;    }} var obj=new Circle (1.0); alert (Obj.area ())

Circle.pi = 3.14159; Can be put into the attribute to write this. pi=3.14159;

Commonly used for the first and third types of

An extended small instance of the third type of notation

var show={        btn:$ ('. Div1 '),        init:function () {            var that=this;            alert (this);            This.btn.click (function () {                    that.change ();                    Alert (this)                ,})                    },        change:function () {            this.btn.css ({' Background ': ' Green '});        }    }    Show.init ();

JS Object-oriented methods 2

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.