js understood prototype chain (3) - configuration borrowing

Construction loan (constructor strealing)

1. Why already exist but also to use prototype inheritance chain structure borrow

First look at this example

function Super(){
        this.sets = [0,1,2];
    }
    Super.prototype.age = 100;
    
    function Sub(){
        this.subValue = 100;
    }
    Sub.prototype = new Super();
    Sub.prototype.setAge = function(){
        console.log(this.subValue);
    }

    var obj1 = new Sub();
    obj1.sets[0] = 200;

    var obj2 = new Sub();
    console.log(obj2.sets[0]);

The resulting output is 200, using only the prototype chain, but a change in its property value created by the object structure inherited property values ​​yet to change the structure, which is of course not want things to be seen.

Why is there such a situation

The reason is that: 

= New new Sub.prototype Super (); after Sub.prototype = {set: [0, 1, 2], __proto __: ...} set property is instantiated, obj1.set is acquired attribute Sub prototype object, 
because it is a reference type, the value is modified.

So how to change this value is modified problem. Use construction loan constructor strealing, I think this is not a direct translation, construction theft is to use the structure to initialize other people own this

 subnew object Sub constructed, its properties are set to regenerate, because the time of creation, this will go to Super theft method initializes this, Sub been defined sets of this property.

Corresponds Sub () {this.sets = [0,1,2]} thus achieving a superclass inheritance of the reference type. Which can be transferred call parameters, to achieve special initialization value.

 

to sum up: 

From the normal to the constructor super class constructor is defined reference value type is initialized to the use configuration. The value of construction will be when the object is initialized, the re going to create, to occupy memory space.

So if I want to use both the prototype chain to achieve the realization of some of the basic variable initialization and methods to reduce memory usage, and want the structure to initialize a reference type variable, how to achieve it? Using Group

Co-inheritance, also known as the classic inheritance.

 

Guess you like

Origin www.cnblogs.com/chenyi4/p/11981447.html