this是Javascript语言的一个关键字。 它代表函数运行时,自动生成的一个内部对象,只能在函数内部使用。比如,
function test(){ this.x = 1; }随着函数使用场合的不同,this的值会发生变化。但是有一个总的原则,那就是this指的是,调用函数的那个对象。
这是函数的最通常用法,属于全局性调用,因此this就代表全局对象 Window。 请看下面这段代码,它的运行结果是1。
function test(){ this.x = 1; alert(this.x); } test(); // 1为了证明this就是全局对象,我对代码做一些改变:
var x = 1; function test(){ alert(this.x); } test(); // 1运行结果还是1。再变一下: var x = 1; function test(){ this.x = 0; } test(); alert(x); //0 说明纯粹的函数调用this指的是window
函数还可以作为某个对象的方法调用,这时this就指这个上级对象。
var x=3; function test(){ alert(this.x); } var o = {}; o.x = 1; o.m = test; o.m(); // 1注意 :如果把o.x=1 注释掉 会怎么样呢?
注释掉出现undefined
会显示undefined 说明如果作为对象调用 只能找到对象的值 var name='marain'; function test(){ console.log(this.name);//marain } test(); var obj={ name:'mps', foo:test //mps } obj.foo(); //--------- var obj = { name: 'qiutc', foo: function() { console.log(this); } } var test = obj.foo; test();//window 为什么是window对象里的函数如果复制给变量就和对象没什么关系了,当一个普通函数执行。
var obj = { name: 'qiutc', foo: function() { console.log(this); }, foo2: function() { console.log(this); // object setTimeout(this.foo, 1000); //window } } obj.foo2();为什么setTimeout 里面展示的是window??
但是在 setTimeout 中执行的 this.foo,却指向了全局对象,这里不是把它当作函数的方法使用吗?这一点经常让很多初学者疑惑;其实,setTimeout 也只是一个函数而已,函数必然有可能需要参数,我们把 this.foo 当作一个参数传给 setTimeout 这个函数,就像它需要一个 fun 参数,在传入参数的时候,其实做了个这样的操作 fun = this.foo,看到没有,这里我们直接把 fun 指向 this.foo 的引用;执行的时候其实是执行了 fun() 所以已经和 obj 无关了,它是被当作普通函数直接调用的,因此 this 指向全局对象。怎么拿到想要的object呢?
var obj = { name: 'marain', foo: function() { console.log(this); }, foo2: function() { console.log(this); var _this = this; setTimeout(function() { console.log(this); // Window console.log(_this); // Object {name: "qiutc"} }, 1000); } } obj.foo2();所谓构造函数,就是通过这个函数生成一个新对象(object)。这时,this就指这个新对象。
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(o.x); // 1运行结果为2,表明全局变量x的值根本没变。
apply()是函数对象的一个方法,它的作用是改变函数的调用对象,它的第一个参数就表示改变后的调用这个函数的对象。因此,this指的就是这第一个参数。
var x = 0; function test(){ alert(this.x); } var o={}; o.x = 1; o.m = test; o.m.apply(); //0apply()的参数为空时,默认调用全局对象。因此,这时的运行结果为0,证明this指的是全局对象。 如果把最后一行代码修改为o.m.apply(o); //1 运行结果就变成了1,证明了这时this代表的是对象o。
这里除了apply 还有一个值得注意的地方:call 这个函数 和apply 几乎相同的作用,但是参数的方式不同