0

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>
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

1

If you want to bind a function to a certain context, you can use bind. It creates a copy of a function where this is set to whatever you pass to it.

b = new Button(f.s.bind(f));
Mike Cluck
  • 31,869
  • 13
  • 80
  • 91
0

this in a function is bound to whatever you called it from. So calling,

this.func();

Is the exact same thing as calling

b.func();

Which means that this in func will get bound to b. That's why console.log(this.x) prints 0: because b.x is 0.

4castle
  • 32,613
  • 11
  • 69
  • 106