在前端工作中不可避免的要经常使用函数,this指向是函数中很重要的内容。今天文汇文汇软件小编就来为大家分享一下。
一.普通函数 this 指代全局对象
function test(){
this.x = 1;
alert(this.x);
}
test(); // 1
二.作为对象方法调用,this 指代上级对象
function test(){
alert(this.x);
}
var o = {};
o.x = 1;
o.m = test;
o.m(); // 1
三.构造函数 this 指代new 出的实例对象
function test(){
this.x = 1;
}
var o = new test();
alert(o.x); // 1
//运行结果为1。为了表明这时this不是全局对象,我对代码做一些改变:
var x = 2;
function test(){
this.x = 1;
}
var o = new test();
alert(x); //2
四.定时器函数 this指的是window
foo.prototype.bar=function(){
setTimeout(function(){alert(this)},3000);
}
var f=new foo;
f.bar()//[object Window]
下一篇: 在前端工作中如何搭建vueui