我在 Javascript 中有一个旧式类,我想在没有完整子类化的情况下利用另一个旧式类的行为。像这样:
function Foo(x) {
this.x = x;
}
Foo.prototype.add1 = function() {
return this.x + 1
}
function Bar(n) {
this.x = 2*n;
}
Bar.prototype.add1 = function() {
// steal behavior from Foo.add1
return Foo.prototype.add1.call(this);
}
这在浏览器控制台中运行良好:
> b = new Bar(3)
Bar {x: 6}
> b.add1()
7
有没有办法改用bind
?有点像
function Bar(n) {
this.x = 2*n;
}
Bar.prototype.add1 = Foo.prototype.add1.bind(xyz);
除了在对象实际存在之前没有用于 xyz
的“this”对象。
以下代码有效,但似乎有误....
function Bar(n) {
this.x = 2*n;
this.add1 = Foo.prototype.add1.bind(this);
}
有没有办法在设置旧式类的原型(prototype)时以这种方式使用bind
?
最佳答案
您不需要使用bind
,只需分配Bar.prototype.add1 = Foo.prototype.add1
。 bind
方法对实例有用,对类不有用。
关于javascript - 使用 bind 来利用另一个 Javascript 类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59380621/