javascript bind函数笔记

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8" />
    <title>Hello Bind!</title>
  </head>
  <body>
    <div id="example"></div>
    <script type="text/javascript">
      this.x = 9;
        var module = {
          x: 81,
          getX: function() { return this.x; }
        };

        module.getX(); // 81

        var retrieveX = module.getX;
        retrieveX(); // 9, because in this case, "this" refers to the global object

                          //这里相当于把getX的函数体赋给了一个全局对象,this自然就变了



        // Create a new function with 'this' bound to module
        //New programmers (like myself) might confuse the global var getX with module's property getX

        //这里创建一个新的函数和retrieveX 一样也就是和getX一样,但是this指向module
        var boundGetX = retrieveX.bind(module);
         boundGetX(); // 81
    </script>
  </body>
</html>

猜你喜欢

转载自xuhang1128.iteye.com/blog/2281688