Tri*_*sie 5 javascript oop jquery
我知道在下面的代码中,undefined如果我点击按钮,它会打印出来,因为在按钮this.field的上下文中而不是Container. 我的问题是如何访问this.field的Container时候this.func被传递到另一个函数,这比一个不同的上下文范围Container。
function Container(){
this.field = 'field';
$('button').click(this.func);
}
Container.prototype.func = function(){
console.log(this.field);
}
Run Code Online (Sandbox Code Playgroud)
我知道我可以做到这一点,但有更好的方法吗?因为我宁愿在构造函数之外定义方法,所以我不会把它弄乱。
function Container(){
var thisObj = this;
this.field = 'field';
$('button').click(function(){ console.log(thisObj.field) });
}
Run Code Online (Sandbox Code Playgroud)
将对象引用作为事件数据传递:
function Container(){
this.field = 'field';
$('button').click(this, this.func);
}
Container.prototype.func = function(e){
console.log(e.data.field);
}
Run Code Online (Sandbox Code Playgroud)
请参阅此处: http: //jsfiddle.net/gilly3/nwtqJ/
| 归档时间: |
|
| 查看次数: |
1161 次 |
| 最近记录: |