Problems in javascript prototype objects (3)

Although the prototype object can share the properties and methods of all instances, its limitations are also obvious. This is because of the sharing feature, which also causes the biggest problem of the prototype. The properties and methods in the prototype will be shared by all objects: static.

function Person(){

}

Person.prototype = {
    constructor:Person , 
    name: 'z3' , 
    age:  20 , 
    job : 'programmer' ,
    friends : ['Li Si','Wang Wu'] ,
    sayName : function(){alert('My name!')}
};  


var p1 = new Person();
var p2 = new Person();  

p1.friends.push('Zhao Liu');

alert(p1.friends); //Li Si, Wang Wu, Zhao Liu
alert(p2.friends); //Li Si, Wang Wu, Zhao Liu
alert(p1.sayName == p2.sayName); //true

Therefore, we usually use prototypes and constructors

function Person(name , age , friends , job){
    this.name = name ; 
    this.age  = age ; 
    this.friends = friends ;
    this.job = job ;
}

Person.prototype = {
    constructor: Person ,  //Do not consider the ergodic problem
    sayName : function(){
        alert(this.name);
    }
};

var p1 = new Person('z3' , 20 , ['Wang Wu','Zhao Liu'] , 'Technical director');
var p2 = new Person('Li Si', 25 , ['Wang Wu','Zhao Liu' ,'Zhao 7'] ,'boss');

alert(p1.friends);  //Wang Wu, Zhao Liu
p1.sayName();  //z3
alert(p2.friends); //Wang Wu, Zhao Liu, Zhao 7
p2.sayName(); //Li Si

Dynamic prototype mode

It is to encapsulate information into functions, which embodies the concept of encapsulation

function Person(name , age , friends , job){
    this.name = name ; 
    this.age  = age ; 
    this.friends = friends ;
    this.job = job ;

    //Dynamic prototyping method:
    if( typeof this.sayName != 'function'){
        Person.prototype.sayName = function(){
            alert(this.name);
        };
    }
}

Safe constructor

The so-called secure mode is that there is no public attribute, and other methods do not reference this object. The secure mode is most suitable for use in a secure environment. If your program has a high security requirement, it is very suitable for this prototype mode

function Person(name , age , job){
        // Create an object to return
        var obj = new Object();
        //You can define private variables and functions private
        var name = name ; 
        //var sex = 'male';
        //var saySex = function(){};
        //Add a method
        obj.sayName = function(){
            alert(name);
        }
        return obj ;                
}
var p1 = new Person('Zhang San');
p1.sayName();

Tags: Attribute

Posted on Sat, 09 May 2020 13:08:43 -0400 by miraclewhipkey