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