简体   繁体   中英

Why is the scope of a javascript function passed as a parameter 'window' — and how do I make the scope its parent class?

Consider the following code:

 var myClass = { bar: function(){ document.getElementById('display').innerHTML = this; // this is 'window' -- but I would like it to be 'myClass' }, foo: function(callback){ callback(); } } myClass.foo(myClass.bar); 
 The scope is: <span id='display'></span> 

Why is the scope of bar 'window' instead of 'myClass' when it is called from a callback parameter -- and how do I make the scope 'myClass'?

When you are passing the function object, myClass.bar to myClass.foo , only the function object bar is passed. It doesn't know about which object it was from. So, there is no relation between myClass and bar in foo function.

Why is the scope of bar 'window' instead of 'myClass' when it is called from a callback parameter

Since callback is not attached to any object, JavaScript will by default, use the global object ( window object) as the this value.

how do I make the scope 'myClass'

Its actually called context, not scope. To fix it, you can explicitly bind myClass , with Function.prototype.bind , like this

myClass.foo(myClass.bar.bind(myClass));

I think you want to do this:

var myClass = {
  bar: function(){
     console.log(this.str); 
  },
  foo: function(callback){
    callback.apply(this); // --> set this as the scope
  },
  str:3
}

myClass.foo(myClass.bar); // outputs 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM