仅针对特定函数调用更改 "this"
Change the "this" only for a specific function call
假设我有这段代码(这是一个简化的例子):
// A Thing that expands other thing can use it's origin Thing's "init".
ThingThatExpands.super = function() {
this.__originThing.init.apply(this, arguments);
}
// I make a Car Thing and give a color and a speed.
var Car = Thing("Toy Car", {
init: function(color, speed) {
this.color = color;
this.speed = speed;
}
});
// Then I make a Racing Car, which inherits the color and speed properties from it's origin
// (that's "Car", of course), but also has a cool sound!
var RacingCar = ThingThatExpands(Car, "Toy Police Car", {
init: function() {
this.super("#00F", 180);
this.sound = "Wee-ooh! Wee-ooh!"
}
})
现在,由于 "RacingCar" 是 "Car" 的 "child",它具有自己的属性和一个不错的 "super" 函数,可用于调用 "Car's" 初始化。
好的。问题是:由于 "super" 函数将 "child" 事物作为 "this",它会更改 "child" 属性,对吗?好的,这就是我们需要的。
但是...这也意味着 "super" 将从 "child" 而不是 "origin" 事物调用,这不应该发生(并且不会起作用)。
我能以某种方式 "protect" 调用 "this.super" 吗?
要更改特定函数的作用域,您必须将该函数绑定到所需作用域的对象。
因此,如果您希望调用 foo.bar()
,但在 baz
的范围内,如果您希望函数立即 运行,请使用 foo.bar.call(baz)
,或者如果您希望它在 运行 时在应用程序中调用它时使用该范围,请使用 foo.bar.bind(baz)
。
假设我有这段代码(这是一个简化的例子):
// A Thing that expands other thing can use it's origin Thing's "init".
ThingThatExpands.super = function() {
this.__originThing.init.apply(this, arguments);
}
// I make a Car Thing and give a color and a speed.
var Car = Thing("Toy Car", {
init: function(color, speed) {
this.color = color;
this.speed = speed;
}
});
// Then I make a Racing Car, which inherits the color and speed properties from it's origin
// (that's "Car", of course), but also has a cool sound!
var RacingCar = ThingThatExpands(Car, "Toy Police Car", {
init: function() {
this.super("#00F", 180);
this.sound = "Wee-ooh! Wee-ooh!"
}
})
现在,由于 "RacingCar" 是 "Car" 的 "child",它具有自己的属性和一个不错的 "super" 函数,可用于调用 "Car's" 初始化。
好的。问题是:由于 "super" 函数将 "child" 事物作为 "this",它会更改 "child" 属性,对吗?好的,这就是我们需要的。 但是...这也意味着 "super" 将从 "child" 而不是 "origin" 事物调用,这不应该发生(并且不会起作用)。
我能以某种方式 "protect" 调用 "this.super" 吗?
要更改特定函数的作用域,您必须将该函数绑定到所需作用域的对象。
因此,如果您希望调用 foo.bar()
,但在 baz
的范围内,如果您希望函数立即 运行,请使用 foo.bar.call(baz)
,或者如果您希望它在 运行 时在应用程序中调用它时使用该范围,请使用 foo.bar.bind(baz)
。