技术控

    今日:151| 主题:49194
收藏本版 (1)
最新软件应用技术尽在掌握

[其他] Understanding "This" in JavaScript

[复制链接]
ポ奉ポ奉糖 发表于 2016-10-3 12:40:24
121 0

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x
Conceptual Overview of “this”

  When a function is created, a keyword called    thisis created (behind the scenes), which links to the object in which the function operates.  
  The    thiskeyword’s value has nothing to do with the function itself, how the function is called determines this’s value  
  Default “this” context

  1. // define a function
  2. var myFunction = function () {
  3.   console.log(this);
  4. };
  5. // call it
  6. myFunction();
复制代码
What can we expect the    thisvalue to be? By default,    thisshould always be the window Object, which refers to the root—the global scope.  
  Object literals

  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };
复制代码
What would be the    thiscontext here?…  
  
       
  • this === myObject?   
  • this === window?   
  • this === anything else?  
  Well, the answer is    We do not know.  
  Remember    The this keyword’s value has nothing to do with the function itself, how the function is called determines the      thisvalue      
  Okay, let’s change the code a bit…
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var myObject = {
  5.   myMethod: myMethod
  6. };
复制代码
Is it clearer now?
  Of course, everything depends on how we call the function.
      myObjectin the code is given a property called    myMethod, which points to the    myMethodfunction. When the    myMethodfunction is called from the global scope, this refers to the window object. When it is called as a method of    myObject, this refers to    myObject.  
  1. myObject.myMethod() // this === myObject
  2. myMethod() // this === window
复制代码
This is called    implicit binding  
  Explicit binding

  Explicit binding is when we explicitly bind a context to the function. This is done with    call()or    apply()**  
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var myObject = {
  5.   myMethod: myMethod
  6. };
  7. myMethod() // this === window
  8. myMethod.call(myObject, args1, args2, ...) // this === myObject
  9. myMethod.apply(myObject, [array of args]) // this === myObject
复制代码
Which is more precedent, implicit binding or explicit binding?
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var obj1 = {
  5.     a: 2,
  6.     myMethod: myMethod
  7. };
  8. var obj2 = {
  9.     a: 3,
  10.     myMethod: myMethod
  11. };
  12. obj1.myMethod(); // 2
  13. obj2.myMethod(); // 3
  14. obj1.myMethod.call( obj2 ); // ?????
  15. obj2.myMethod.call( obj1 ); // ?????
复制代码
Explicit binding takes precedence over implicit binding, which means you should ask first if explicit binding applies before checking for implicit binding.
  1. obj1.myMethod.call( obj2 ); // 3
  2. obj2.myMethod.call( obj1 ); // 2
复制代码
###Hard binding
  This is done with    bind()(ES5).    bind()returns a new function that is hard-coded to call the original function with the    thiscontext set as you specified.  
  1. // Only EC5
  2. myMethod.bind(myObject);
  3. myMethod(); // this === myObject
复制代码
Hard binding takes precedence over explicit binding.
  1. var myMethod = function () {
  2.     console.log(this);
  3. };
  4. var obj1 = {
  5.     a: 2
  6. };
  7. var obj2 = {
  8.     a: 3
  9. };
  10. myMethod = myMethod.bind(obj1); // 2
  11. myMethod.call( obj2 ); // 2
复制代码
New binding

  1. function foo(a) {
  2.     this.a = a;
  3. }
  4. var bar = new foo( 2 );
  5. console.log( bar.a ); // 2
复制代码
So    thiswhen the function has been called with new refers to the new instance created.  
  When a function is called with new, it does not care about implicit, explicit, or hard binding, it just creates the new context—which is the new instance.
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };0
复制代码
API calls

  Sometimes, we use a library or a helper object which does something (Ajax, event handling, etc.) and it calls a passed callback. Well, we have to be careful in these cases. Example:
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };1
复制代码
Take a look at the code. You might think that because we are passing “this.onSomethingCoolDone” as a callback, the scope is implicit. That’s wrong, you are passing a reference to that method and not to the way to call it.
  To fix this, there are a few ways:
  
       
  • Usually libraries offer another parameter called scope ( as we do in our library in Pages), so then you can pass the scope you want to get back.  
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };2
复制代码

       
  • You can hard bind the method to the scope you want (ES5).  
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };3
复制代码

       
  • You can create a closure and cache      thisinto      me. For example:  
  1. var myObject = {
  2.   myMethod: function () {
  3.     console.log(this);
  4.   }
  5. };4
复制代码
I do not recommend this approach because it can cause memory leaks and it tends to make you forget about the real scope and rely on variables. You can get to the point where your scope is a real mess.
  This problem applies also to event listeners, timeouts, forEach, etc.
  Understanding “this” is an extensive topic, I recommend the following readings:
  
       
  •       You don’t know js - this & Object prototypes   
  •       code plus article   
  •       toddmotto article  
  ###Related tutorials you might be interested in
友荐云推荐




上一篇:Use JUnit's Expected Exceptions Sparingly
下一篇:【技术分享】一探小米Analytics后门
酷辣虫提示酷辣虫禁止发表任何与中华人民共和国法律有抵触的内容!所有内容由用户发布,并不代表酷辣虫的观点,酷辣虫无法对用户发布内容真实性提供任何的保证,请自行验证并承担风险与后果。如您有版权、违规等问题,请通过"联系我们"或"违规举报"告知我们处理。

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读

扫码访问 @iTTTTT瑞翔 的微博
回页顶回复上一篇下一篇回列表手机版
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )|网站地图 酷辣虫

© 2001-2016 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表