【问题标题】:Class method calling another class' method that is stored as an argument [duplicate]类方法调用存储为参数的另一个类的方法[重复]
【发布时间】:2016-12-03 10:09:23
【问题描述】:

对不起,这个令人困惑的标题,我不知道如何问这个。 我有一个关于类和方法的问题。我有一个按钮,按下时会调用另一个对象的函数。对于此示例,它应该将“100”作为 f 的“x”记录到控制台,但它会记录“0”:我的按钮的“x”。帮忙?

<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>

【问题讨论】:

    标签: javascript function class methods arguments


    【解决方案1】:

    如果要将函数绑定到某个上下文,可以使用bind。它会创建一个函数的副本,其中 this 设置为您传递给它的任何内容。

    b = new Button(f.s.bind(f));
    

    【讨论】:

    • 完美运行,谢谢!
    【解决方案2】:

    this 在函数中绑定到您调用它的任何内容。所以打电话,

    this.func();
    

    和打电话是一回事

    b.func();
    

    这意味着func 中的this 将绑定到b。这就是console.log(this.x) 打印0 的原因:因为b.x0

    【讨论】:

      猜你喜欢
      • 2022-01-22
      • 2011-03-07
      • 2015-08-01
      • 1970-01-01
      • 2015-02-22
      • 1970-01-01
      • 1970-01-01
      • 2022-12-04
      • 1970-01-01
      相关资源
      最近更新 更多