Sorry for the confusing title, I have no clue how to ask this. I have a question regarding classes and methods. I have a button that, when pressed, calls another object's function. For this example, it should log "100" to the console as f's "x", but instead, it logs "0": my button's "x". Help?
<script>
function fun(x){
this.x = x;
}
fun.prototype = {
s:function(){
console.log(this.x);
}
}
function Button(func){
this.x = 0;
this.y = 0;
this.w = 1000;
this.h = 1000;
this.func = func;
}
Button.prototype = {
check_if_click:function(x, y){
if (x >= this.x && x <= this.x + this.w && y >= this.y && y <= this.y + this.h){
this.func();
}
}
}
f = new fun(100);
b = new Button(f.s);
b.check_if_click(500, 500);
</script>
答案 0 :(得分:1)
如果要将函数绑定到某个上下文,可以使用bind
。它会创建一个函数的副本,其中this
设置为传递给它的任何内容。
b = new Button(f.s.bind(f));
答案 1 :(得分:0)
this
绑定到您调用它的任何内容。所以打电话,
this.func();
与调用
完全相同b.func();
这意味着this
中的func
将绑定到b
。这就是console.log(this.x)
打印0
的原因:因为b.x
是0
。