Class method calling another class' method that is stored as an argument

时间:2016-07-28 20:28:44

标签: javascript function class methods arguments

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>

2 个答案:

答案 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.x0