Why are my JavaScript object properties being overwritten by other instances?

后端 未结 2 605
忘了有多久
忘了有多久 2020-11-28 13:55

I created an object like the following.

var BaseObject = function(){

var base = this;
base.prop;

base.setProp = function(val){
    base.prop = val;
}
}
         


        
2条回答
  •  生来不讨喜
    2020-11-28 14:31

    There is only one BaseObject instance from which all TestObjects inherit. Don't use instances for creating prototype chains!

    What you want is:

    var TestObject = function(){
        BaseObject.call(this); // give this instance own properties from BaseObject
        // do something
    }
    TestObject.prototype = Object.create(BaseObject.prototype);
    

    See JavaScript inheritance: Object.create vs new, Correct javascript inheritance and What is the reason to use the 'new' keyword at Derived.prototype = new Base for a detailed explanation of the problems with new. Also have a look at Crockford's Prototypal inheritance - Issues with nested objects

提交回复
热议问题