javascript原型继承覆盖方法

时间:2017-10-11 10:19:31

标签: javascript prototype

这是我现在所拥有的

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

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

new o = Proto();

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

我希望这可以打印" world"因为我覆盖了这个方法。任何帮助表示赞赏。

2 个答案:

答案 0 :(得分:2)

请参阅以下代码段:

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

输出将是:

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

在调用new MyClass().print()时,引擎将首先检查对象本身中是否有print。否则,它将检查原型链。实际上,this.print = ...覆盖了MyClass.prototype.print = ...。不确定覆盖在这种特定情况下是否正确,但我会使用隐藏

答案 1 :(得分:0)

你需要了解原型链是如何工作的,首先引擎在当前对象中找到函数,即Proto对象,因为up()在那里可用,所以它不会在原型中搜索。但如果它没有用Proto对象编写,那么它将在原型中搜索它。

以下是我撰写的关于prototype and inheritance的文章。