this的话是执行上下午中的一个重要属性,对于this的规范解读的话可以去看一下这篇文章:规范解读this。
对象中调用
函数中的this和作用域链不一样,作用域链的话是在函数定义的时候就定义好了的,然而this的话是变化的,对于函数来说就是谁调用这个函数,this指向谁。
关于函数的谁调用this指向谁我是这么理解的:
const testThis = {
nameThis: 'this',
getNameHandler: function () {
console.log(this.nameThis);
}
}
testThis.getNameHandler(); // 打印的结果是 this
// 这就说明getHandler中的this指向的是testThis这个对象,也就是谁调用this指向谁,调用者是testThis这个对象
函数中调用
函数中调用的时候,this的指向始终指向的是window(不考虑严格模式),严格模式下this不会指向window,而是undefined。
const testThis = {
nameThis: 'this',
getNameHandler: function () {
console.log(this.nameThis);
}
}
const midVar = testThis.getNameHandler
midVar() // 打印的结果为undefined,this的指向转为了winodw(不考虑严格模式的情况下)
通过new关键字的调用
new操作符进行的调用,this指向的是创建后的对象,因为new操作符会改变this的指向,改成了new操作符创建后的对象。
function newTests(){
this.name = 'newTests';
console.log(this, 'this') // 是testNews这个对象
}
const testNews = new newTests;
console.log(testNews.name) // newTests
看一下构造函数有返回值的情况
function newTests(){
this.name = 'newTests';
console.log(this, 'this')
return {}
}
const testNews = new newTests;
console.log(testNews.name) // undefined,这说明testNews是返回的空对象
下边这个图片打印的是这个函数中的this,说明只是new操作符返回的时候判断了一下,并不是改变了this。
new 操作符模拟实现
function newFn () {
const obj = Object.create({});
const Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
const res = Constructor.call(obj, arguments);
return typeof res === 'object' ? res : obj; //在这里判断的是否是对象,是对象进行返回构造函数的返回值,不是对象则返回这个obj
}