初学JavaScript经常被this绕晕,所以我总结一下JavaScript中的this。
首先声明本文讨论的是非严格模式下的this,因为严格模式下this进入运行环境前是禁止指向全局变量的,默认undefined。(什么是严格模式?阮一峰大神博客的传送门)
既然说到这儿了,顺便摘录上面博客的一个例子(因为很像面试题)
function f(){
return !this;
}
// 返回false,因为"this"指向全局对象obj window,"!this"就是false
function f(){
"use strict";
return !this;
}
// 返回true,因为严格模式下,this的值为undefined,所以"!this"为true。
全局上下文
最简单的例子
console.log(window===this)//true,浏览器里全局对象就是window(假设是在浏览器环境下)
console.log(document.this===document);//true
注意,这种情况严格模式和非严格模式是一样的
函数上下文
直接调用
this指向全局变量window
function f0(){
f1(){
console.log(this);//指向全局变量window
}
f1();
}
f0();
对象方法中的this
这种情况下this会被绑定到调用它的对象
var obj={
p:function(){
console.log(this);//obj
}
}
obj.p();
原型链中的this
this还是指向调用它的对象,只是方法可以从原型链上继承
var o={
f:function(){
console.log(this.a);
}
};
var p=Object.create(o);
p.a=1;
p.f();//p从原型链上继承f方法,输出1,this指向调用它的p
构造函数中的this
this与即将被创建的新对象绑定
function Car(){
this.color='red';
this.maxspeed=100;
}
var car1=new Car();
console.log(car1.color);//'red'
console.log(car1.maxspeed);//100
.call()、.apply()
function isAdult(name,age){
if(age<18){
console.log(name+" is not an adult");
}else {
console.log(name+" is an adult");
}
}
function Person(name,age){
this.name=name;
this.age=age;
isAdult.call(this,name,age);
/*isAdult.apply(this,arguments); 这里如果用apply也是一样的*/
}
var user1=new Person('Tom',10),//Tom is not an adult
user2=new Person('Wang',22);//Wang is an adult
.call()、.apply()函数本身的作用就是将函数运行上下文环境绑定到传入的第一个参数所指的环境上,上例就是使用了这种方法
DOM事件中的this
btn.on('click', function(){
console.log(this)//this指向btn
}
DOM事件的this指向触发事件的元素
这里再举一个例子,如果不想要this指向btn怎么办?
var p={
var self=this;
bind:btn.on('click', function(){
console.log(this)// 绕开this,self指向p
}
}
setTimeout()、setInterval()中的this
setTimeout()、setInterval()中的this指向全局对象
document.addEventListener('click', function(event){
console.log(this);//this指绑定事件的dom节点
setTimeout(function(){
console.log(this);//全局对象,浏览器里就是window
}, 200);
}, false);
可以对比两个this,输出结果不一样
内联事件处理函数中的 this
当代码被内联处理函数调用时,它的this指向监听器所在的DOM元素:
<button onclick="alert(this.tagName.toLowerCase());">
Show this
</button>
注意只有外层代码中的this是这样的,下面的this按照前面所讲函数上下文情况中的直接调用,指向全局对象window:
<button onclick="alert((function(){return this}}()));">
Show inner this
</button>
网友评论