我是靠谱客的博主 故意心锁,这篇文章主要介绍js的this指针,现在分享给大家,希望可以做个参考。

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

1、函数调用

复制代码
1
2
3
4
5
function test() { this.v = 1; alert(this.v); } test(); //1

this指向全局对象window

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

复制代码
1
2
3
4
5
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、作为对象方法调用

复制代码
1
2
3
4
5
6
7
function test() { alert(this.v); } var o = {}; o.v = 1; o.m = test; o.m(); //1

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

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

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

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
(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、作为构造函数

复制代码
1
2
3
4
5
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。

复制代码
1
2
3
4
5
6
7
8
9
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


最后

以上就是故意心锁最近收集整理的关于js的this指针的全部内容,更多相关js内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(62)

评论列表共有 0 条评论

立即
投稿
返回
顶部