Summarize _javascript skills of several common writing methods of JS object-oriented

Source: Internet
Author: User

Define circle class, owning member variable r, constant pi, and member function area ()

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);  
Alert (C.area ());

3.json wording

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

4. It's a bit of a change, but the essence is 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 as the first and third

Extended small instance of the third way of writing

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 ();

Note that this is the point of issue

The above summary of JS Object-oriented Several common writing summary is small series to share all the content of everyone, hope to give you a reference, but also hope that we support the cloud-dwelling community.

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.