【发布时间】:2015-10-10 00:59:06
【问题描述】:
我有以下简单的继承模式,我想知道是否可以按照我在构造函数中的方式调用方法(基本上,使用this 而不是“超级原型”。
父类,Pet
function Pet(name) {
this.name = name;
this.nickname = name;
this.adopt();
}
Pet.prototype.adopt = function() {
this.nickname = 'Cutty ' + this.name;
}
Pet.prototype.release = function() {
this.nickname = null;
}
Pet.prototype.cuddle = function() {
console.log(this.name + ' is happy');
}
子类,Lion
function Lion(name) {
Pet.prototype.constructor.apply(this, arguments); // super(name)
this.cuddle();
this.release();
}
Lion.inherits(Pet);
Lion.prototype.adopt = function() {
// DTTAH
}
Lion.prototype.release = function() {
Pet.prototype.release.call(this);
console.log('Thanks for releasing ' + this.name);
}
inherits 助手(我知道 polyfill 很糟糕)
Function.prototype.inherits = function(Parent) {
function ProtoCopy() {}
ProtoCopy.prototype = Parent.prototype;
this.prototype = new ProtoCopy();
this.prototype.constructor = this;
}
我的宠物像这样被实例化var lion = new Lion('Simba')
在 Lion 构造函数中,
我可以在调用子/父类方法时继续使用this 吗?或者我应该直接使用父原型中的方法吗? (例如对super() 或release() 的伪调用)
我问的原因是:
-
this运行时替换 -
constructor财产并不总是我们所想的(从我在这里和那里读到的)
我不确定这些东西如何影响生成的对象。
感谢您的启发!
【问题讨论】:
-
你的
inherits函数有副作用,我推荐使用Object.create。 -
您应该在任何地方省略
.prototype.constructor部分。 -
Pet.prototype.constructor.release();超级调用是错误的。你的意思可能是Pet.prototype.release.call(this); -
我不想提供这个作为一个完整的答案,而是一个建议考虑看看 Klass.js github.com/ded/klass - 它允许轻松调用
this.super()。 -
@elclanrs 有什么副作用?这是我最自信的部分!
标签: javascript inheritance methods constructor