Summary of js Object Oriented Programming

  • 2021-07-21 07:31:08
  • OfStack

//Defines the Circle class, the member function area () with the member variable r, the constant PI, and the computed area

1. Factory approach


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


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 type 1 type 1


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 attributes written as this. PI = 3.14159;

Types 1 and 3 are commonly used

Extended small examples 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();

Related articles: