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

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

提交回复
热议问题