[英]Don't understand why this JavaScript function can be called one way but not the other
我最近開始學習JavaScript以創建HTML5游戲,並且遇到了我很難理解的行為。
舉例來說,我有一個構造函數,它使用每次游戲更新(例如動畫,移動等)時應執行的一系列動作來初始化新的精靈。 該JSFiddle演示了一個基本實現。
本質上,我對為什么這不起作用感到困惑...
Sprite = function () {
this.actions = [this.animate];
};
Sprite.prototype = {
animate: function () { /* animate the sprite */ },
update: function () {
this.actions[0](); // doesn't do anything (?)
}
};
...但是
Sprite = function () {
this.actions = [this.animate];
this.holder = 'whatever';
};
Sprite.prototype = {
animate: function () { /* animate the sprite */ },
update: function () {
this.holder = this.actions[0];
this.holder(); // executes animate function as desired
}
};
在我的經驗不足的人看來,兩個示例似乎都應該做完全相同的事情。 那么,為什么沒有發生,如果我叫this.actions[0]()
直接,但如果我給你this.actions[0]
到this.holder
,然后調用this.holder()
它工作得很好?
當一個函數被調用時,值將被分配到所謂的局部變量this
函數內部。
除非您做了一些更改(例如new
, bind()
, call()
, apply()
),否則該值將是調用它的對象。 使用foo.bar()
this === foo
bar
函數中的this === foo
。
this.actions[0]()
使得this
等於的值actions
屬性
this.holder()
使得this
等於任何的值this
是在呼叫功能。
您的功能必須依賴this
的值才能執行任何操作。
解決此問題的兩種方法:
Sprite = function () {
this.actions = [this.animate.bind(this)];
};
要么:
update: function () {
this.actions[0].call(this);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.