在前端开发工作中中不能防止的要常常应用涵数,this偏向是涵数中太重要的內容。今日文汇文汇手机软件/a>网编就来为大伙儿共享一下。
一.一般涵数 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]