简体   繁体   English

javascript原型继承覆盖方法

[英]javascript prototype inheritance overwriting methods

Here's what I have now这是我现在所拥有的

var Proto = function(){
    this.up = function(){ alert('hello'); };
};

Proto.prototype.up = function(){ alert('world'); };

new o = Proto();

alert(o.up); // prints "hello"

I would expect this to print "world" since I overwrite the method.我希望这会打印“世界”,因为我覆盖了该方法。 Any help is appreciated.任何帮助表示赞赏。

See the following snippet:请参阅以下代码段:

var MyClass = function () {
    this.print = function logAttachedToThis() { console.log('hello'); };
};
MyClass.prototype.print = function logAttachedToPrototype() { console.log('world'); };
console.log(new MyClass());

Output will be:输出将是:

MyClass {print: ƒ}
print: ƒ printAttachedToThis()
__proto__:
  print: ƒ printAttachedToPrototype()
  constructor: ƒ ()
  __proto__: Object

When invoking new MyClass().print() , the engine will first check whether print is available in the object itself.调用new MyClass().print() ,引擎将首先检查对象本身是否有print可用。 Otherwise, it will check in the prototype chain.否则,它将检查原型链。 So actually, this.print = ... is overriding MyClass.prototype.print = ... .所以实际上, this.print = ...覆盖了MyClass.prototype.print = ... Not sure overriding is the right word in this specific case though, I would use hiding instead.虽然不确定在这种特定情况下覆盖是正确的词,但我会改用隐藏

You need to understand how prototype chain works, firstly engine finds the function in the current object ie, Proto object, as up() is available there so it will not search in the prototype.您需要了解原型链是如何工作的,首先引擎会在当前对象中找到函数,即 Proto 对象,因为 up() 在那里可用,所以它不会在原型中搜索。 But if it was not written in Proto object then it will search it in the prototype.但是如果它不是写在 Proto 对象中,那么它会在原型中搜索它。

Here is an article on prototype and inheritance written by me.这是我写的一篇关于原型和继承的文章。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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