是否可以在JavaScript類中調用父方法,但是仍然可以訪問父類和子類中的原型方法。下面是代碼示例:在JavaScript類中調用父方法,但可以訪問對象實例內的原型方法嗎?
var Base = function() {
this.baseMethod = function(){
return 'baseMethod';
};
this.baseInitMethod = function() {
return 'baseInitMethod';
}
}
Base.prototype.basePrototypeMethod = function() {
return "basePrototypeMethod";
};
var Specific = function() {
Base.call(this);
this.baseInitMethod = function() {
// call baseInitMethod from Base class
}
this.specificMethod = function(){
return 'specificMethod';
}
this.specificInitMethod = function() {
return this.basePrototypeMethod();
}
}
Specific.prototype.specificPrototypeMethod = function() {
return 'specificPrototypeMethod' + '-' + this.baseInitMethod();
}
for(var p in Base.prototype) {
Specific.prototype[p] = Base.prototype[p]
}
var s = new Specific();
console.log(s.baseMethod());
console.log(s.baseInitMethod());
console.log(s.basePrototypeMethod());
console.log(s.specificMethod());
console.log(s.specificInitMethod());
console.log(s.specificPrototypeMethod());
我想從baseInitMethod方法調用baseInitMethod在基類特殊類中,但讓所有的功能從上面仍然有效調用。那可能嗎?
當然,你想要什麼休息繼承的約定?如果你想分享一個方法,創建一個可供兩者使用的第三個類。 – Alex 2014-10-03 12:00:30
你能舉個例子嗎? – 2014-10-03 12:14:09