考虑这段代码:
function Parent(){};
Parent.prototype.myMethod = function()
{
return "hi!";
}
function Child(){};
Child.prototype = Object.create(new Parent());
var objChild = new Child();
//no override...
var output = objChild.myMethod();
alert(output); // "hi!"
//override and detect that in Parent.myMethod()
Child.prototype.myMethod = function()
{
var output = Parent.prototype.myMethod.call(this);
alert("override: " + output); // "hi!"
};
objChild.myMethod();
是否可以“自然地”或通过“覆盖”确定Parent.myMethod()
是否被调用,并且在这种情况下返回其他内容?
答案 0 :(得分:1)
是否可以“自然地”或通过“覆盖”
来确定是Parent.myMethod()
不是真的(不使用非标准,已弃用的caller
property)。但是,您可以检测何时在具有不同myMethod
属性的对象上调用方法:
this.myMethod === Parent.prototype.myMethod
并且在那种情况下返回别的东西?
你真的不应该。使它成为您期望别的东西的参数(but beware),或者用两种不同的方法划分功能。
答案 1 :(得分:0)
在我看来,你不要覆盖这个方法,方法是将this
传递给你调用函数的调用函数,就像它是Child
的函数一样,你可以即使你没有从Parent
继承,也要这样做。