简体   繁体   中英

why I can't “overwrite” a method in javascript?

I would like to override a function of a JS object by adding it to its prototype.

var originalObject = function(){
    this.someFun = function(){
        // ...
    }
}

var otherObj = function(){
    this.otherFun = function(){
        originalObject.prototype.fun =  function(){
            return 'This is the overwritten function.';
        }
        var o = new originalObject();
        return o.fun()
    }
}

This way when I execute new otherObj().otherFun() I have the expected result ( 'This is the overwritten function.' ), but if the function I'm trying to add is already part of originalObject

var originalObject = function(){
    this.fun = function(){
        return 'This is the original function';
    }
    this.someFun = function(){
        // ...
    }
}

Then the result is not the expected one, infact new otherObj().otherFun() returns 'This is the original function' .

so, is this the only way to add the method to the prototype and override it? And most important why I can't "overwrite" the function in the prototype?

In js objects there are two levels which are depend on directly object and depend on directly prototype. And when you call a property which is in object, it starts to search from the root then looks in branches. You can see the tree belowed picture: 在此处输入图片说明

因为该函数已经存在于对象中,所以它将被调出,而不是在对象原型中寻找它。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM