js的this指针

来源:互联网 发布:回转企鹅罐 知乎 编辑:程序博客网 时间:2024/04/30 05:51

this是js的一个关键字,指向当前函数的调用对象。

1、函数调用

function test() {this.v = 1;alert(this.v);}test(); //1

this指向全局对象window

另一种形式可以证明this指向window

var v = 1;function test() {this.v = 2;}test(); //2

只要是function test(){} or test()这种形式,在函数内部,this都指向window。

eg:

test.method = function() {

function test() {

//this指向window

}

}

var test = obj.method;

test(); //函数内,this指向window而非obj。

2、作为对象方法调用

function test() {alert(this.v);}var o = {};o.v = 1;o.m = test;o.m(); //1

函数作为某个对象的方法调用的时候,this指向的是当前函数的调用对象。

经典例子(实现点击start按钮,启动计时;点击stop按钮,暂停当前计时):

涉及知识点(闭包、setInterval&setTimeout区别、this指针)。

(function() {function counter(num) {this.num = num;}; counter.prototype = {   show: function() {       document.getElementById('text').innerHTML = this.num++;   },   start: function() {       //此时this指向函数调用对象c       this.stop();       var me = this;  //保存当前this指向的对象c       //setInterval为window对象的方法,它的第一个参数的函数在全局作用域执行,因此this指向window,要想调用show(),必须先缓存c,       console.log(this === c);    //true,this指向c       this._timer  = setInterval(function() {           console.log(this === c);    //false,this指向window           me.show();       }, 1000);   },   stop: function() {       clearInterval(this._timer);   }};    var c = new counter();    c.start();})();

3、作为构造函数

function test() {this.v = 1;}var o = new test();alert(o.v); //1

也就是说作为构造函数的时候,this指向的是新对象。

4、apply调用

apply( )在犀牛书里面的解释是,调用一个对象的方法,以另外一个对象替换当前对象,也就是改变当前函数的作用域。

当使用Function.prototype的call( obj, 1, 2, 3)  or apply(obj, [1, 2, 3])方法时,函数的this指向函数的第一个参数,也就是obj。

var v = 1;function test() {alert(this.v);}var o = {};o.v = 2;o.m  = test;o.m.apply(); //这里要注意,当apply( )参数为空的时候,默认调用window。所以这里alert出来的是1

若改为o.m.apply(o); //2