[英]Is there a way to call parent’s method from a child when the method doesn’t belong to parent's prototype?
我已經了解了當方法駐留在父級原型中時如何調用父級方法。 但是,有一種方法可以在不屬於其原型的情況下調用parent的方法?
假設我們有以下示例:
(function () {
function Parent() {
this.myMethod2 = function(){
return 'Parent' + this.test;
};
}
Parent.prototype.myMethod = function () {
return 'Parent ' + this.test;
};
function Child() {
Parent.call(this);
this.myMethod = function(){
return 'Child >> ' + Parent.prototype.myMethod.call(this);
};
this.myMethod2 = function(){
return 'Child >> ' + Parent.myMethod2.call(this); // Uncaught TypeError: Cannot read property 'call' of undefined
};
}
var c = new Child();
c.test = 'test';
console.log(c.myMethod());
console.log(c.myMethod2());
})();
在這里, c.myMethod()可以正常工作。
但是c.myMethod2()導致錯誤“未捕獲的TypeError:無法讀取未定義的屬性'call'”
關於什么 :
function Parent() {
this.myMethod2 = function(){
return 'Parent' + this.test;
};
}
function Child() {
Parent.call(this);
var old = this.myMethod2;
this.myMethod2 = function(){
return 'Child >> ' + old.apply(this, arguments);
};
}
說明:在字段中存儲功能時; 它的行為與普通對象完全相同,因此,如果影響新值,則需要引用舊值。 當事物沒有存儲在原型中時,就會發生這種情況。
編輯:我在應用中添加了參數。 Apply具有優勢,能夠使用指定為數組的args調用函數。 “參數”是一個預定義名稱,用於存儲傳遞給當前函數的參數,對可變參數或類似的重載有用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.