new constructor

function Cat(name,age){
    this.name = name
    this.age= age
}
@ Mechanism 1: each object has a function prototype object 
the console.log (Cat.prototype)           // Node Output: {} 
Cat.prototype.get_name = function () {
     return  the this .name
}

// Mechanism 2: new keyword + constructor 
    // step1: create a new object {}, the object has a default __propto__ objects 
    // step2: the this constructor to the new object {} this --- > {} 
    // Step3: the prototype object constructor is copied to the new object {} __propto__ 
    @ Step4: returns a new object 
    // the new object becomes the constructor example 
the let CAT1 = new new Cat ( 'baizhu ', 1 )
console.log(cat1)
const cat2 = new Cat('heizhu',2)
console.log(cat2)
console.log(cat2.__proto__)

// mechanism 3: search mechanism (attribute method instance the search priority) 
     // When the properties of the instance method call, first search examples of their properties and methods, if not go __proto__ where to find 
    the let cat3 = new new Cat ( 'Dawang',. 3 )
    cat3.name =. 4 
    cat3.get_name = function () {
         return 'my own way:' + the this .name
    }
    console.log (cat3.name)           // the Node Output: 4 
    console.log (cat3.get_name ())     // the Node Output: my own way: 4


// Advanced: How a handwriting function, it has a new + constructor function (for example, how to create a new_cat function, it has a new Cat () function?) 
    Function new_cat (name, Age) {
         // step1 : create a new object {}, the object has a default target __propto__ 
        the let newobj = {}
        .__ propto__ newobj = {}
         // Step2: the this constructor point the this new object} --- {> {} 
        Cat.call (newobj, name, Age)
         // Step3: the prototype object constructor is copied to the new shallow {} of object __propto__ 
        for (the let Key in Cat.prototype) {
            newObj.__propto__[key] = Cat.prototype[key]
        }
         // Why is not that far above newObj .__ propto_ = Cat.prototype? Because this is a shallow copy rather than direct assignment 
        return newobj
    }
    console.log(new_cat('shouxie',5)) 
    /*
        Output node:
        {     __propto__: Cat { get_name: [Function] },
            name: 'shouxie',
            age: 5
        }
    */
   
   
   // If __proto__ instances where the method to redefine what happens? 
    new new Cat ( 'baizhu',. 1) get_name = .__ proto __. function () {
         return '_ changed manually _propto:' + the this .name
    }
    console.log(new Cat('baizhu',1).get_name()) 
    /*
        Output node: manually changed _propto_: baizhu
    */
    
    
    

 

Guess you like

Origin www.cnblogs.com/BlueCc/p/11669248.html