javascrpt之this指向问题

一:就近原则,this指向当前调用上下文;    也可以理解为局部变量覆盖全局变量。     如:

 var foo = "foo";
   var myObject = {
       foo: 'Hello World'    
   };

   var sayHello = function(){
     console.log(this.foo);
   };

   myObject.sayHello = sayHello;   
   myObject.sayHello();        //   Hello World

   sayHello();                // foo      

 

二: 嵌套函数内部的this都失去方向,都指向了window对象

 

三:一个疑惑点,javascript中不是function也是对象吗?    为什么function里的this不会指向自己呢? 

  this指向当前调用上下文!!!!!!!!!!!!   是谁调用它,让它执行的就指向谁!       自动执行函数,它的this还是指向它的宿主的。

       如何实现在嵌套层级中保证this的指向不变?

var myObject = {

      myProperty: "hello world",
      myMethod: function(){
          console.log(this);    //  调用这个方法它才会执行
          var that = this;      //  当前this指向 myObject       保留this的指向  
          var helperFunction = function(){     // 嵌套 此时this只想Window object
              console.log(this);
              console.log(that.myProperty);     //  hello world    that的指向指向myObject    
          }()
      }
  };
  myObject.myMethod();


//  (function hello(){
//      alert(this);
//  })();

 

 

四.call  apply控制this的指向 

var myObject = {};
  var myFunction = function(param1,param2){
      this.foo = param1;     // this指向它的调用上下文
      this.bar = param2;
      console.log(this);    // myObject
  };
  myFunction.call(myObject,'foo','bar')    // 与其说call改变了this的指向,不如说this始终指向它的调用上下文而已 

  

 

一: 一个this指向问题
let a = console.log console.log(a) // 打印正常 ƒ log() { [native code] } a('1') // 打印正常 1 let v = document.write console.log(v) // 打印正常 ƒ write() { [native code] }
v('cccc') // 报错啦:Uncaught TypeError: Illegal invocation

改进



  

 

 

参考文章:

1-  https://segmentfault.com/a/1190000018270750

2- https://zhuanlan.zhihu.com/p/23804247

3- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind#Polyfill

1-  es6  ployfill

1-   https://segmentfault.com/a/1190000015724112

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

     

posted @ 2017-11-04 17:17  风茗  阅读(394)  评论(0编辑  收藏  举报