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

后端 未结 2 593
忘了有多久
忘了有多久 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

    0 讨论(0)
  • 2020-11-28 14:40

    Think of protoypal inheritance as dealing solely with objects and without the concept of classes. In your code you have a BaseObject object which has a prop attribute. You have 2 other objects that extend from 1 instance of that object, but the property belongs to the original object. If you need each object to have their own copy, then they need to be given a distinct variable that is intialized for that object (such as in their constructor).

    As an aside the Java style accessors are overkill in JavaScript (you can intercept access natively if needed) and can further muddy these questions since they will behave differently.

    0 讨论(0)
提交回复
热议问题