this的指向问题一直以来都是前端开发者找工作面试的重点,现在就聊聊这个this到底是何方神圣?
ECMAScript中这样写到:this关键字执行为当前执行环境的thisBinding.
MDN这样写到:绝大多数中,函数的调用决定了this的指向。
简单来说,this的指向是由于调用时候决定的,this具有运行期绑定的特性。
全局执行上下文:
在全局执行上下文中,this的指向为window
console.log(this === window) // true
在浏览器里面this等价于window对象,如果你声明一些全局变量,这些变量都会作为this的属性。
函数执行上下文:
在函数执行上下文,this的指向取决于函数的调用方式。
function test() { return this === window } test() // true
直接调用,this就会指向全局window.
var obj = { name: 'cat', age: 3, say: function () { console.log(this.name) } } obj.say() // cat
指向调用的对象,这里this指向的对象为obj.
构造函数的this:
构造函数的创建的对象会有以下操作:
所以this就是指向创建的这个对象上。
function Person(name){ this.name = name; this.age = 25; this.say = function(){ console.log(this.name + ":" + this.age); } } var person = new Person("axuebin"); console.log(person.name); // axuebin person.say(); // axuebin:25
DOM事件处理函数:this指向触发事件的元素,也就是始事件处理程序所绑定到的DOM节点。
var ele = document.getElementById("id"); ele.addEventListener("click",function(e){ console.log(this); console.log(this === e.target); // true })
这里的this指向e.target.
箭头函数的this:箭头函数不会创建自己的this,它只会从自己的作用域链的上一层继承this。因此,在下面的代码中,传递给setInterval的函数内的this与封闭函数中的this值相同:
function Person(){ this.age = 0; setInterval(() => { this.age++; // |this| 正确地指向 p 实例 }, 1000); } var p = new Person();
这就是令人讨厌的this指向哪里的讲解,比较简单,但是容易忽略。。。。
本文来源:CSDN,转载请注明出处!
来源地址:https://blog.csdn.net/leelxp/article/details/107130930
最新内容
© 2016 - 2023 chengxuzhixin.com All Rights Reserved.