Why is it impossible to change constructor function from prototype?

前端 未结 3 529
别那么骄傲
别那么骄傲 2020-11-30 20:24

I have such example.

function Rabbit() {
    var jumps = \"yes\";
};
var rabbit = new Rabbit();
alert(rabbit.jumps);                    // undefined
alert(Ra         


        
3条回答
  •  日久生厌
    2020-11-30 21:16

    This is wonderful workaround creating an object from a literal, not from constructor function.

    Firstly, if you want jumps member to be contained in the object, rather than being just a local variable in the constructor then you need this keyword.

    function Rabbit() {
        this.jumps = "yes";
    };
    
    var rabbit = new Rabbit();
    alert(rabbit.jumps);                    // not undefined anymore
    

    And now you can easily now access jumps publicly the way you wanted:

    rabbit.jumps = 'no';
    alert(rabbit.jumps);                    // outputs 'no' 
    

    But still if you create another Rabbit object it will initially have 'yes' as defined in the constructor, right?

    var rabbit2 = new Rabbit();
    alert(rabbit.jumps);                     // outputs 'no' from before
    alert(rabbit2.jumps);                    // outputs 'yes'
    

    What you could do is creating a Rabbit from some default Rabbit Object. The concrete rabbits will always have the default value from default Rabbit object even when you change it on the fly unless you have changed the value in concrete rabbit object (implementation). This is a different than @Juan Mendes's solution which is probably the best but it can open another point of view.

    Rabbit = {jumps : 'yes'};    // default object
    
    rabbit = Object.create(Rabbit);
    Rabbit.jumps = 'no';
    rabbit2 = Object.create(Rabbit);
    
    console.log(rabbit.jumps);   // outputs "no" - from default object
    console.log(rabbit2.jumps);  // outputs "no" - from default object
    
    // but...
    rabbit.jumps = 'yes';
    Rabbit.jumps = 'unknown';
    
    console.log(rabbit.jumps);   // outputs "yes" - from concrete object
    console.log(rabbit2.jumps);  // outputs "unknown" - from default object
    

提交回复
热议问题