一、this
當前的 關鍵字 函數(shù)的擁有者
1.函數(shù)中的引用
var x = 1;
function test() {
this.x = 0; // this==test
};
function test1() {
this.x = 2; // this ==> test1
}
test();
test1();
console.log(x) //==> 2 從上往下按照順序執(zhí)行
2.在對象中調用
function test3(){
return this.a; //this,指向調用者 obj.action;
}
var obj = {}
obj.a =1;
obj.action =test3;
console.log(obj.action()); //==>1
3.構造函數(shù)
this指向實例化以后的對象
function Person(age,name) {
this.name = name;
this.age = age;
}
var fun = new Person('xiao1',22);
var fun2 = new Person('xiao2',22);
console.log(fun.name);
例:面試題
var number = 1;
var object1 = {
number:2,
showNumber:function(){
this.number = 3;
(function(){
console.log(this.number); //==>1
})();
console.log(this.number); //==>3
}
};
object1.showNumber();
考點:函數(shù)自執(zhí)行 this指向的是window