[英]Why doesn't this use of javascript functions in an array work?
我正在嘗試創建一個函數數組,所以我可以根據索引調用一個。 設置功能不起作用。 setF1和setF2函數可以。 使事情以這種方式運作的設計決策是什么?
您可以在jrootham.tjddev.net/test/test.html找到測試頁面
我似乎無法粘貼測試代碼。
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript">
var thing =
{
f1 : function() {alert(1);},
f2 : function() {alert(2);},
setF1 : function() {this.call = this.f1;},
setF2 : function() {this.call = this.f2;},
list : [this.f1, this.f2],
set: function(index){this.call=this.list[index];},
call : this.f1
}
</script>
</head>
<body>
<button type="button" onClick="thing.set(0)">Set 0</button>
<button type="button" onClick="thing.set(1)">Set 1</button>
<button type="button" onClick="thing.setF1()">Set F1</button>
<button type="button" onClick="thing.setF2()">Set F2</button>
<button type="button" onClick="thing.call()">Call</button>
</body>
</html>
這不起作用的原因是因為this
在call:this.f1
的上下文中call:this.f1
實際上是引用window
而不是 thing
。
this
只是參考thing
從內部 thing
的成員函數。
但是,以下方法將起作用:
var thing = { //watch out for semicolon insertion...
f1 : function() {alert(1);},
f2 : function() {alert(2);},
setF1 : function() {this.call = this.f1;},
setF2 : function() {this.call = this.f2;},
set: function(index){ this.call=this.list[index]; },
call : function() {
this.f1();
}
};
thing.list = [thing.f1, thing.f2];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.