是否可以在 JavaScript 类中调用父方法,但仍然可以从父类和子类访问原型(prototype)方法。这是代码示例:
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,但上面的所有函数调用仍然有效。这可能吗?
最佳答案
您的Specific.prototype
对象应该继承自Base.prototype
对象。目前,您正在使用以下代码将其所有属性复制到对象:
for(var p in Base.prototype) { Specific.prototype[p] = Base.prototype[p] }
但你实际上应该使用 Object.create
建立真正的原型(prototype)链:
Specific.prototype = Object.create(Base.prototype);
Specific.prototype.specificPrototypeMethod = function() {
return 'specificPrototypeMethod' + '-' + this.baseInitMethod();
}
<小时/>
I want to call baseInitMethod in Base class from baseInitMethod method inside Specific class
是的。在您的 Specific
构造函数中,您首先需要获取 Base
的 baseInitMethod
实例方法,然后再覆盖实例的属性:
function Specific() {
Base.call(this);
var parentInitMethod = this.baseInitMethod;
this.baseInitMethod = function() {
// call baseInitMethod from Base class:
parentInitMethod.call(this /*, arguments…*/);
}
…
}
so that all function calls from above still works.
我不确定你的意思到底是什么。 specificPrototypeMethod
将始终调用当前实例的 baseInitMethod
,该实例将是 Specific
的覆盖方法,而不是 中定义的原始方法>基础
。
关于javascript - 在 JavaScript 类中调用父方法,但仍然可以访问对象实例内的原型(prototype)方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26178519/