只要创建函数,Javascript就会为它创建一个this关键字,可以在函数作用域中访问this,它引用函数所在的对象。换句话说,this引用的是把当前函数作为方法的对象:
var person = {
name:'tony',
age: 25,
gender:'male',
getGenderMethod:function(){
//return this.gender; 第一种方式
// return person.gender;第二种方式
}
};
console.log(person.getGenderMethod());//测试以上2种方式结果都是male
函数作用域中的this引用拥有它的对象,而非函数自身。(使用new关键字和call()或apply()的情况除外)。
那么如何确定this的值?
this的值在函数被调用时根据相应的执行环境确定:
var name = 'jack';
var person = {name:'tony'};
var sayName = function(s){
console.log(s + this['name']);
};
person.sayName = sayName;//为person定义sayName属性,并让它引用sayName函数
person.sayName('person.sayNmae:');
sayName('globle sayName:');
通过person调用的sayName方法,可以看到this引用的就是person,
在全局作用于中调用的sayName方法,this引用的就是window对象.
下面来看下在嵌套的函数中,this引用的对象是什么:
var myFunc = {
func1: function(){
console.log(this);//this引用调用对象myFunc
var func2 = function(){
console.log(this);//顶级对象window
var func3 = function(){
console.log(this);//顶级对象window...
}();
}();
}
}
myFunc.func1();
在嵌套的函数中,this引用的是window对象.
那如何在嵌套的函数中,使用自己需要的this引用的对象,看下面例子:
var person = {
name:'my name is jack!',
eatMethod: function(){
var thisObject = this;//保存this的引用.
console.log(this);
var innerFunc = function(){
console.log(thisObject.name);
console.log(this);
}();
}
}
person.eatMethod();
可以利用作用域链保存传递我们需要的this的引用对象。
正常情况下,this的值由函数被调用时的执行环境确定(使用new关键字时除外)。还有使用call()和apply()控制this值的特殊情况,下一节在来学习。