JavaScript中的this指向总结

29次阅读

共计 2492 个字符,预计需要花费 7 分钟才能阅读完成。

关于 javascript 中 this 指向的总结
浏览器环境
在全局作用域中,this 的指向是 window 对象
console.log(this);
//Window 对象
console.log(this === window);
//true
ES5 函数中 this 的指向
在非严格模式下, 函数中的 this 指向 window 对象,因为此时函数 fn 是 window 的一个属性,所以运行 fn 时,fn 中的 this 指向 window。其实 this 的指向就是指向函数的运行时环境。
var fn = function () {
console.log(this);
console.log(this === window);
}
fn();
//Window 对象
//true
在严格模式下,若不使用 window 调用函数,函数中的 this 指向 undefined;使用 window 调用时,指向的时 window 对象。
var fn = function () {
‘use strict’
console.log(this);
console.log(this === window)
}
fn();
//undfined
//false
window.fn();
//Window 对象
//true
在严格模式下有一种例外的情况,就是在定时器中的 this,此时无论使用 window 调用还是不使用 window 调用,this 都指向 window。
var fn = function () {
‘use strict’
setTimeout(functioin(){
console.log(this);
console.log(this === window);
},1000)
}
fn();
//Window 对象
//true
在 ES6 中箭头函数 this 的指向
在 ES6 中箭头函数 this 的指向取决于定义时环境中的 this 指向一致
var fun = () => {
console.log(this);
console.log(this === window);
}
fun();
//Window 对象
//true
// 定义箭头函数时, 就是这个过程:()=>{…} 所在的环境是 window,所以运行 fun() 时,箭头函数内部的 this 指向 window
var obj = {
name:’Jay’,
age:25,
fn:()=>{console.log(this)},
fun:function(){
console.log(this)
}
};
// 在定义 fn 时,fn 内部 this 的指向就是定义 obj 对象时所在的环境,obj 所在的环境是 window,所以调用 obj.fn() 时,返回的 this 就是 Window 对象
obj.fn(); //Window 对象
obj.fun();//{name: “Jay”, age: 25, fn: ƒ, fun: ƒ}
var name = ‘Kobe’;
var obj = {
name:’Jay’,
age:25,
fn1:function(){
return function(){
console.log(this.name);
}
},
fn2:() =>{
return () => {
console.log(this.name);
}
}
};
var fnn1 = obj.fn1();
var fnn2 = obj.fn2();
fnn1();//Kobe
fnn2();//Kobe
在 DOM 事件中的 this 指向
DOM 事件处理函数中 this 的指向是触发该事件的对象
<div id=’app’>App</div>
<script>
var $id = document.querySelector(‘#app’);
$id.onclick = function () {
console.log(this);
}
</script>
// 当点击 App 时,console.log(this), 打印出来的值时 <div id=’app’>App</div>
构造函数中的 this 指向
构造函数中的 this 的指向是通过构造函数所创建出的对象实例
function Person (){
this.name = ‘Jay’,
this.age = 25;
console.log(this);
}
var p1 = new Person();
//Person {name: “Jay”, age: 25}
改变 this 的指向
可以使用 call()、apply()、bind() 改变函数内部 this 的指向(ES6 中的箭头函数除外)。其中 call() 和 apply() 在传入要绑定的 this 指向时,立即执行。bind() 在传入要绑定的 this 指向时,并不执行,需要再次调用才会执行。
使用 call() 改变 this 的指向
var obj = {
name:’Jay’,
age:25
};
function fn(){
console.log(this === obj);
console.log(this);
}
fn.call(obj);
//true
//{name: “Jay”, age: 25}
使用 apply() 改变 this 的指向
var obj = {
name:’Jay’,
age:25
};
function fn(){
console.log(this === obj);
console.log(this);
}
fn.apply(obj);
//true
//{name: “Jay”, age: 25}
使用 bind() 改变 this 的指向
var obj = {
name:’Jay’,
age:25
};
function fn(){
console.log(this===obj);
console.log(this);
}
//fn.bind(obj); 不会立即执行,需要再次调用才会执行。
var fn1 = fn.bind(obj);
fn1();
//true
//{name: “Jay”, age: 25}
需要注意的是,当使用 call()、apply()、bind() 改变函数内部 this 的指向时, 如果传入的不是一个对象,会调用相对的构造函数,进行隐式类型装换。
function fn(){
console.log(typeof this === ‘object’);
console.log(this);
}
fn.apply(‘I am a string’);
//true
//String{“I am a string”}

正文完
 0