Home >Web Front-end >JS Tutorial >Summary of several common object-oriented code writing methods in JavaScript

Summary of several common object-oriented code writing methods in JavaScript

伊谢尔伦
伊谢尔伦Original
2017-07-22 13:31:011229browse

1. Factory way


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 method

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. There is a slight 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 the attribute and written as this.PI=3.14159;

Commonly used as the first and third types

Extended small example of the third writing method


var show={
    btn:$('.p1'),
    init:function(){
      var that=this;
      alert(this);
      this.btn.click(function(){
          that.change();
          alert(this);
        })
      
    },
    change:function(){
      this.btn.css({'background':'green'});

    }
  }
  show.init();

What needs to be noted is the pointing problem of this

The above is the detailed content of Summary of several common object-oriented code writing methods in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn