1

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?

Community
  • 1
  • 1
bncc
  • 478
  • 7
  • 18
  • 1
    Try to see http://stackoverflow.com/questions/4933288/overwrite-function-of-existing-object-in-javascript – vanadium23 Apr 29 '15 at 13:43
  • I suppose inheritance goes from parents to children. If you have two functions, one in the prototype and another in an object which inherits from it, the function in the object (the child) overrides the one in the prototype. So: you are overriding the function in the prototype, but not in the object. – Fernando Apr 29 '15 at 13:54

2 Answers2

2

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: enter image description here

uzay95
  • 16,052
  • 31
  • 116
  • 182
0

Because the function already existed in object, it will be called out instead of being looked for in objects prototype.

Chiến Nghê
  • 736
  • 2
  • 9
  • 25