让我们假设我有类似的东西
function x(a,b,c){
this.a = a;
this.b = b;
this.c = c;
}
x.prototype.z = function(){
var ele = document.createElement("a");
a.onclick = this.y;
}
x.prototype.y = function(){
// How can i use access to a,b,c?
// If i use this.a, this.b or this.c it wont work because this is
//referencing "ele".
}
所以我的问题是..在将y定义为某个元素onclick事件后,如何在y函数上访问a,b,c变量?
---------我的解决方案--------
经过一些思考和白皮书的研究后,我通过使用 .bind()得到了这个,因为DenysSéguret说,并且我使用 event.target 来保持“a”
function x(a,b,c){
this.a = a;
this.b = b;
this.c = c;
}
x.prototype.z = function(){
var ele = document.createElement("a");
a.onclick = this.y.bind(this);
}
x.prototype.y = function(event){
var clickSource = event.target;
var objectBridge = this;
}
答案 0 :(得分:0)
您必须绑定函数以确保在调用回调时上下文是正确的:
a.onclick = this.y.bind(this);