改变"这个"仅用于特定的函数调用

时间:2015-11-24 19:59:20

标签: javascript class oop object 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",它有它的属性和一个很好的"超级"可以用来打电话的功能" Car"初始化。

好的。问题是:因为"超级"功能给孩子"作为"这",它将改变孩子"属性,对吗?好的,那就是我们需要的。 但是......这也意味着"超级"将从"孩子"不是"起源"事情,这不应该发生(并且不会起作用)。

我可以以某种方式"保护" " this.super"调用

1 个答案:

答案 0 :(得分:2)

要更改特定函数的作用域,必须将该函数绑定到所需作用域的对象。

因此,如果您希望foo.bar()被调用,但需要baz范围,请使用foo.bar.call(baz),如果您希望该功能正确运行,或使用foo.bar.bind(baz)如果你希望它在运行时在应用程序中调用它时使用该范围。