Javascript doesn't call prototype method

I am trying to override the method, and the script:

function wrapper(target) { target.doABC = function () { alert('in wrapper'); }; return target; } function Model() { wrapper(this); } Model.prototype.doABC = function () { alert('in Model'); }; var a = new Model(); a.doABC(); 

The result is "wrapped". I do not know why?

+6
source share
2 answers

Any JavaScript object has its own and inherited properties. Native ones are those that are defined directly in the instance, and the inherited ones are taken from the prototype object.
When using the property attribute, JavaScript first searches the object’s own property list. If the property is not found, it searches the object's prototype chain.

In your example, the wrapper() method defines on the object instance its own doABC property, which is a function that notifies 'in wrapper' . Even if the object has a prototype with the same doABC property that notifies 'in Model' , JavaScript will use its own property anyway.

 function wrapper(target) { // Define an own property "doABC" target.doABC = function () { alert('in wrapper'); }; return target; } function Model() { wrapper(this); } // Define an inherited property "doABC" Model.prototype.doABC = function () { alert('in Model'); }; var a = new Model(); //Use the own property "doABC". The inherited "doABC" is ignored. a.doABC(); 

As a complement, you can delete your own property using the delete operator. Once deleted, the object will use the inherited property.

 // delete the own property "doABC" delete a['doABC']; // the inherited "doABC" will be used. Alerts "in Model" a.doABC(); 

Check out the full working demo .

+5
source

Let me see if I can explain:

Here you have two separate versions of doABC .

Your target.doABC creates a function specific to this instance of your Model , and each Model gets its own doABC .

Since Model has doABC , the JavaScript engine should not look for a "chain" for something else, so it will never look for a version of Model.prototype.doABC .

You can see this by adding the following lines:

 Model.prototype.doXYZ = function () { alert('in Model'); }; 

and challenge

 a.doXYZ(); 

Since a does not have its own doXYZ , then and only then it will look for the chain and see the method in the prototype.

+1
source

All Articles