【Javascript中this指向】

在对象内部的方法中使用对象内部的属性是一个非常普遍的需求。但是 JavaScript 的作用域机制并不支持这一点,基于这个需求,JavaScript 又搞出来另外一套 this 机制。

var bar = { 
	myName:"闷倒驴", 
	printName: function () { console.log(myName) } 
}
let myName = '王美丽';
bar.printName(); // '王美丽'
var bar = { 
	myName:"闷倒驴", 
	printName: function () { console.log(this.myName) } 
}
let myName = '王美丽';
bar.printName(); // '王美丽'

作用域链和 this 是两套不同的系统,它们之间基本没太多联系

2. this在哪里可以使用

全局上下文中的this

console.log(this)来打印出来全局执行上下文中的 this,最终输出的是 window 对象。所以你可以得出这样一个结论:全局执行上下文中的 this 是指向 window 对象的。这也是 this 和作用域链的唯一交点,作用域链的最底端包含了 window 对象,全局执行上下文中的 this 也是指向 window 对象

函数上下文中的this

  • 在全局环境中调用一个函数,函数内部的 this 指向的是全局变量 window。

  • 通过一个对象来调用其内部的一个方法,该方法的执行上下文中的 this 指向对象本身

function foo(){
    // 'use strict';
	console.log(this)
};
foo() // window

3. this指向总结

this指向总结

  • 当函数被正常调用时,在严格模式下,this 值是 undefined,非严格模式下 this 指向的是全局对象 window;

  • 通过一个对象来调用其内部的一个方法,该方法的执行上下文中的 this 指向对象本身

  • ES6 中的箭头函数并不会创建其自身的执行上下文,所以箭头函数中的 this 取决于它的外部函数

  • new 关键字构建好了一个新对象,并且构造函数中的 this 其实就是新对象本身

    • 当执行 new CreateObj() 的时候,JavaScript 引擎做了如下四件事:
      • 首先创建了一个空对象 tempObj;
      • 接着调用 CreateObj.call 方法,并将 tempObj 作为 call 方法的参数,这样当 CreateObj 的执行上下文创建时,它的 this 就指向了 tempObj 对象;
      • 然后执行 CreateObj 函数,此时的 CreateObj 函数执行上下文中的 this 指向了 tempObj 对象;
      • 最后返回 tempObj 对象。
  • 嵌套函数中的 this 不会继承外层函数的 this 值。

    var myObj = { 
    	name : "闷倒驴", 
    	showThis: function(){ 
    		console.log(this); // myObj
            var bar = function(){ 
            	this.name = "王美丽"; 
            	console.log(this) // window
            } 
            bar(); 
        }
    };
    myObj.showThis();
    console.log(myObj.name);
    console.log(window.name);
    
    • 解决this不继承的方法

      • 内部函数使用箭头函数
      • 将在外层函数中创建一个变量,用来存储this,内层函数通过作用域链即可访问
      var myObj = { 
      	name : "闷倒驴", 
      	showThis:function(){ 
      		console.log(this); // myObj
              var bar = ()=>{ 
              	this.name = "王美丽"; 
              	console.log(this) // myObj
              } 
              bar(); 
          }
      };
      myObj.showThis();
      console.log(myObj.name);
      console.log(window.name);
      
       

猜你喜欢

转载自blog.csdn.net/m0_62336865/article/details/127129423