this指向

this指向

this指向调用者

普通函数

1
2
3
4
5
6
function t () {
this.age = 25;
}
t();//调用者为null,this为null时,js把this指向window
//在es6以后,this为null时,将抛出异常
//函数内带有this操作,不能直接调用,应该new,否则会污染全局
1
2
3
4
5
6
7
8
9
function intro () {
alert('my name is'+this.name);
}
var dog = {name:'dog',intro:intro};
dog.intro() //dog
var cat = {name:'cat',intro:intro};
cat.intro() //cat
(cat.intro = dog.intro)()// 计算机计算赋值结果

构造函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
function Cat (name,color){
this.name = name;
this.color = color
}
var cat = new Cat();//会得到一个新对象,方法内的this指向该新对象
/*
方法new的瞬间,得到一个空对象 {}
方法的this指向该空对象
运行方法
{}.name = name;
{}.color = color;
返回该对象
*/
console.log(cat)// color:undefined;name:undefined;

call和apply

动态改变this的指向

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<div id="test1"></div>
<div id="test2"></div>
function t(){
this.style.backgroundColor = 'orange';
}
//t.call(test1);
//t.call(test2);
/*
函数名.call(对象,参数1,参数2,参数3......)
1.把函数的this指向对象
2.运行函数,传参为参数1,参数2,参数3......
*/
/*
函数名.apply(对象,[参数1,参数2,参数3......])
*/
1
2
3
4
5
6
7
8
9
10
var name = 'The window';
var obj = {
name:'The obj',
getFunc:function(){
return function () {
return this.name
}
}
}
alert(obj.getFunc()()) //The window