js object oriented

1. Constructor mode Test the first letter of the constructor function is capitalized, and assigns properties and methods to the this object.

 

function CPerson(name,sex,age) {  
this.name = name;  
this.sex = sex;  
this.age = age;  
this.show = function () {  
console.log(this.name+this.sex+this.age);  
}  
}  
var m1 = new CPerson('wyy',' 女',' 23');  
m1.show();  
//wyy female 23

 2. Prototype mode

Every function has a prototype property, which is a pointer to an object. And the purpose of this object is to contain properties and methods that can be shared by all instances of a particular type. That is, the prototype object of the object created by calling the constructor has the advantage of allowing all instances of the object to share its properties. There is no need to define the instance's information in the constructor.

function CPerson(){  
}  
CPerson.prototype.name='wyy';  
CPerson.prototype.sex='女';  
CPerson.prototype.age=23;  
CPerson.prototype.show=function(){  
console.log(this.name+ this.age+  this.sex);  
}  
var m1 = new CPerson();  
m1.show();   
//wyy23 female

3. Combination of Constructor and Prototype Patterns
Use constructors to define instance properties, use prototypes to define methods and shared properties. As a result, each instance has a copy of instance properties, and shares the method reference, which is the most used.

 

function CPerson(name,sex,age) {  
this.name = name;  
this.sex = sex;  
this.age = age;  
}  
CPerson.prototype.show=function(){  
console.log(this.name+this.age+this.sex);  
}  
var m1 = new CPerson('wyy',' 女','23');  
m1.show();  
//wyy23 female

 

 

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326823176&siteId=291194637