如何使用Child的当前上下文(this)调用Child类中的父函数?
我尝试使用Parent.testFunc.call(this);
但是我收到错误(无法读取属性'未定义的调用)。
function extend(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
var Parent = function(){
this.test = function(){
alert("worked");
};
};
var Child = function(){
Parent.call(this);
//THIS GIVES THE ERROR **
Parent.test.call(this);
};
extend(Child, Parent);
var child = new Child();
如何从Child保持相同的上下文(this)调用名为test的父函数?
答案 0 :(得分:0)
在这种情况下,你只需使用
this.test();
...因为函数通过Parent
函数直接附加到实例本身。
示例:
function extend(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
var Parent = function(){
this.test = function(){
console.log("worked");
};
};
var Child = function(){
Parent.call(this);
this.test(this);
};
extend(Child, Parent);
var child = new Child();
通常,创建函数的级别无关紧要,您可以在this
上访问它。唯一的麻烦就是你有一个重新定义的功能。例如,Parent
有test
,然后您还希望Child
拥有自己的test
版本,但需要Child
实例也可以调用Parent
的{{1}}(可能来自test
)。
当您在构造函数中创建函数时,很难安排,但是当您将它们放在原型上时更容易(尽管仍然冗长和笨拙)。
为了完整性:
Child
最后,使用ES2015 + function extend(Child, Parent) {
Child.prototype = Object.create(Parent.prototype);
Child.prototype.constructor = Child;
}
var Parent = function(x){
this.x = x;
};
Parent.prototype.test = function() {
console.log("Parent's test, x = " + this.x);
};
var Child = function(x){
Parent.call(this, x);
this.test(this);
};
extend(Child, Parent);
Child.prototype.test = function() {
Parent.prototype.test.call(this);
console.log("Child's test, x = " + this.x);
};
var child = new Child(42);
语法,该示例更简单:
class
...您现在可以在尖端浏览器上使用,有些可以使用转换(可能使用Babel)。