this
this 本身原本很简单,总是指向类的当前实例。
this的特点:
- 在 function 内部被创建
函数预编译过程中,
- this –> window(this指向window)
- 全局作用域里this –> window
指向调用时所在函数所绑定的对象
- 谁调用这个方法,this就指向谁。obj.func(); func()里面的this指向obj)
- this 不能被赋值,但可以被 call/apply 改变
- call/apply可以改变函数运行时this的指向
例题:
<script type = "text/javascript">
var name = "222";
var a = {
name : "111",
say : function() {
console.log(this.name);
}
}
var fun = a.say;
fun() //222 将a.say放在全局执行
a.say() //111 a调用say方法
var b = {
name : "333",
say : function() {
fun(); //不像别的有调用:a.say,(前面有a.),这个没有,所以就执行预编译(全局的)
}
}
b.say(a.say); //222
b.say = a.say;
b.say(); //333
</script>
//222 111 222 333
练习题:
<script type = "text/javascript">
var foo = 123;
function print() {
this.foo = 234; //this表示的是window里面的,所以把GO的123改成了234
console.log(foo); //指的是GO里面的123,但是前面有this的声明
}
print();
</script>
//234
变形:
<script type = "text/javascript">
var foo = 123;
function print() {
// var this = Object.create(print.prototype) //这里的this不指代window了
this.foo = 234; //AO里面没有foo,所以到GO里面去找
console.log(foo); //指的是GO里面的123,但是前面有this的声明
}
new print();
</script>
//123
例题:
运行test()和new test()的结果分别是什么?
<script type = "text/javascript">
var a = 5;
function test() {
a = 0;
alert(a); //0 0
alert(this.a); //5 undefined
var a;
alert(a); //0 0
}
test();
new test();
</script>
解析:
test()
AO {
a:undefined
this.a:window
}
|
AO {
a:0
this.a:5
}
new test()
AO {
a:undefined
this.a:{}
}
|
new的时候函数里面有var this = Object.create(test.prototype)
或者写成var this = {
__proto__:test.prototype
}
AO {
a:0
this.a:undefined //this上面没有a
}