object in prototype is inherited as reference

后端 未结 2 796
余生分开走
余生分开走 2021-01-21 03:35

I want to inherit new object instance using prototype.

Test case:

var MyObj = function() {}
MyObj.prototype.objName = {} 
// I want this to be a differen         


        
2条回答
  •  面向向阳花
    2021-01-21 03:59

    This means that objects in prototype are not inherited as its copies but instead as its reference.

    Nothing on the prototype is copied - the whole concept of prototypical inheritance is that properties reference the shared properties of the prototype object. So if you want a property to be individual for each instance, you have to explicitly assign it to the object and shadow the prototype property; just as you're doing it with the _objName property in your code.

    But this is not very pretty and the performance of this code is much worse.

    If you want it pretty, move it to the constructor (or make the constructor look for something like an init method to call if exists, then you can create that init method on the prototype.

    To make performance a little better, you can change the getter function to

    MyObj.prototype.getObj = function() {
        var obj = {};
        this.getObj = function(){ return obj; }; // overwrite itself
        return obj;
    };
    

    though it still has the function call overhead. For even more elegance, you can use a getter property (not supported in old browsers) that removes itself on the first access:

    Object.defineProperty(MyObj.prototype, "objName", {
        get: function() {
            var obj = {};
            Object.defineProperty(this, "objName", {
                value: obj,
                writable: true //?
            });
            return obj;
        },
        enumerable: true,
        configurable: true
    });
    

    Now you can omit the function call parenthesis.

提交回复
热议问题