简体   繁体   中英

Why doesn't bind(object) binds this to object inside anoynamous function?


I am pretty new to javascript, and i am facing some problem understanding why my first code is not working as expected. I have read a few articles on "this", but it didn't help.

  var user_obj = {
      some_func : function () {
          alert("hello");
   }}

First code:

Here i am attaching an event listener to some element called elem. The attached function is a property of user_obj, but when i execute it, it gives me error "TypeError: this.some_func is undefined". My doubt is when i am using bind to explicitly bind this to user_obj, why is it giving this error.

document.getElementById("elem").addEventListener("click",(function () {this.some_func.bind(user_obj)})());

Second Code:

This works as expected.

document.getElementById("elem").addEventListener("click",this.some_func.bind(user_obj));

Thanks for the help.

bind() change the value of this inside the function, not outside.

In your first example the anonymous function use this to refer to global object.

If you want the anonymous function uses this to refers to user_obj you need to bind the anonymous function to user_obj , not some_func() , also because some_func() doesn't use this , so there is no need to bind it.

Look at the example: it prints the value of this in the anonymous function, first time binding it to user_obj , second time without binding

 var user_obj = { some_func : function () {alert("hello");} }; document.getElementById("elem").addEventListener("click",(function () {console.log(this)}.bind(user_obj))()); document.getElementById("elem").addEventListener("click",(function () {console.log(this)})()); 
 <div id="elem"></div> 

Your second example works also without the bind() , because again it changes the value inside the function, where this isn't used. But since in your second example the call to the function isn't in an anonymous function, the value of this doesn't change to global object

BTW, it is getElementById() , not getElementByID() (please notice the d of Id )

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