Home > Web Front-end > JS Tutorial > body text

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

伊谢尔伦
Release: 2017-07-22 13:31:01
Original
1175 people have browsed it

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 ) );
Copy after login

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());
Copy after login

3.json writing method


var Circle={
  "PI":3.14159,
 "area":function(r){
     return this.PI * r * r;
    }
};
alert( Circle.area(1.0) );
Copy after login

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())
Copy after login

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();
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!