this从入门到放弃

  • 全局环境里this指向window
  • this指向要在执行时确定(箭头函数除外)
    四种运用场景:
  • call apply bind
  • 作为构造函数执行
  • 作为普通函数执行(函数中this默认指向函数的调用者,全局是window)
  • 作为对象属性执行

在window环境下调用函数,函数中的this也指向window,node里指向global,严格模式下为undefined

<script type="text/javascript"> 
 foo = "bar"; 
 function test() { 
     this.fun = "fun"; 
}  
console.log(this.fun); //logs "bar" 
test();
console.log(this.fun); //logs "fun" 
</script>
<script type="text/javascript">
foo = "bar"; 
function test() {
 this.foo = "foo"; 
}  
console.log(this.foo); //logs "bar"  
new test(); 
console.log(this.foo); //logs "bar" 
 console.log(new test().foo); //logs "foo" 
</script>

函数里面的this其实相对比较好理解,如果我们在一个函数里面使用this,需要注意的就是我们调用函数的方式,如果是正常的方式调用函数,this指代全局的this,如果我们加一个new,这个函数就变成了一个构造函数,我们就创建了一个实例,this指代这个实例,这个和其他面向对象的语言很像。另外,写JavaScript很常做的一件事就是绑定事件处理程序,也就是诸如button.addEventListener(‘click’, fn,false)之类的,如果在fn里面需要使用this,this指代事件处理程序对应的对象,也就是button。

(3)this的指向是由它所在函数被调用时的上下文决定的

(4)闭包相爱相杀系列
var name = "The Window";

    var object = {
        name : "My Object",

        getNameFunc : function(){

            return function(){
                return this.name;
            };

        }

    };

    alert(object.getNameFunc()());

解释:打印出的结果是全局的The Window, 在调用object.getNameFunc()时就将匿名函数作为返回值返回到window,再进行执行,也就如同一般函数的执行,this也就指向window


var name = "The Window";

  var object = {
    name : "My Object",

    getNameFunc : function(){
      var that = this;
      return function(){
        return that.name;
      };

    }

  };

  alert(object.getNameFunc()()); 
引用自阮一峰老师博客
(5)对象中的函数嵌套中的this指向
var food = {
            desc:function(){
                var _this = this;
                console.log(this === food);
                setTimeout(function(){
                    console.log(_this === food);
                },100)
            }
        }
        food.desc();         //嵌套后函数中this指向window

var food = {
            desc:function(){
                //var _this = this;
                console.log(this);
                setTimeout(function(){
                    console.log(this);
                }.bind(this),100)
            }
        }
        food.desc();

使用保存this变量与绑定bind来防止this丢失

(6)构造函数的prototype中,this的指向

在整个原型链中,this指向的都是当前的构造函数实例


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容