//Define the Circle class, have member variable r, constant PI and member function area() that calculates area
1. Factory method
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 writing
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 writing method
var Circle={ "PI":3.14159, "area":function(r){ return this.PI * r * r; }};alert( Circle.area(1.0) );4. A little change, but the essence is the same as the first one
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 properties and written as this.PI=3.14159;
Commonly used are the first and third types
Extended example of the third writing method
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();It should be noted that this pointing problem
The above article summarizes several common writing methods for object-oriented js. This is all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.