对于javascript的初学者来讲,通常对“this”关键字都感到很是迷惑。本文的目的旨在让你全面的了解“this”,理解在每个情景下如何使用“this”,但愿经过本文,能够帮助同窗们不在惧怕“this”!!javascript
其实“this”就是咱们平时用的一个代词。打个简单的比喻:html
“小豆豆是一个很幽默的人,他很是喜欢看《暴走漫画》”java
可是你也能够这样写:jquery
“小豆豆是一个很幽默的人,小豆豆很是喜欢看《暴走漫画》”浏览器
可是平常生活中咱们会一直用这种方式来描述一我的吗?若是你的回答是Yes,好吧,估计再也没有人愿意跟你作朋友了,我没骗你…(开个玩笑:-) )。 因此,人类就发明了这样一种看似高端、洋气、上档次的代名词,说白了javascript中的“this”也就是这么一个东东。闭包
一个简单的例子:app
person = {
firstName: "zhou",
lastName: "Quan",
fullName:function(){
alert(person.firstName + " " + person.lastName);//Zhou Quan
alert(this.firstName + " " + this.lastName);//Zhou Quan
}
}
person.fullName();
咱们能够根据前面所说的方式来理解这个程序的结果, 可是这仅仅停留在表面而已,下面咱们再进行更深一步的理解。ide
首先,咱们知道javascript中全部的函数都拥有属性,就像一个对象也拥有属性同样。当一个函数被执行时,他就拥有了“this”属性--调用this所在函数的对象。this永远指向一个独一无二的对象,这个对象一般包含一个函数/方法,虽然它也能够被用在一个函数以外的全局做用域中(global scope)。注意:在严格模式(strict mode)中,在全局函数或者匿名函数中this的值为“undefined”(也就是说this没有绑定任何对象)。函数
“this”被用在一个函数内部(假设是function A),那么它包含的值是调用“function A”的对象。咱们须要this来访问调用“function A”的对象的属性和方法,特别是当咱们不知道到这个对象名叫什么的时候,或者这个对象没有名字的时候。其实,this就是调用当前函数的对象的一个代名词!this
咱们来举一个简单的例子:
var person = {
firstName: "zhou",
lastName: "Quan",
//this将为person对象,由于person对象会调用FullName方法
FullName:function(){
alert(this.firstName + " " + this.lastName); //zhou Quqn
}
}
person.FullName();
$ ("button").click (function (event) {
// $(this) 的值将是 ($("button")) 对象
// 由于这个button对象调用了 click () 方法
console.log ($ (this).prop ("name"));
});
this是没有被指定值的,直到有一个对象调用了this所在的这个函数(咱们暂且给它一个称号:this Function)。
也就是说,只有当有一个对象调用了this Function以后,this Fuction中的this才被指定!在大多数状况下,this Function被调用以后,this都会被指定一个值,可是,也有少数的状况下this是没有值的,这个问题咱们将在后面进一步探讨。
当一段代码在浏览器中执行时,全部的全局变量和函数都是在“window”对象上定义的。所以,当”this”被用在全局函数中是,他指定的值是”window”对象。咱们来看下面一段代码:
var firstName = "Peter",
lastName = "Ally";
function showFullName () {
// "this" inside this function will have the value of the window object
// because the showFullName () function is defined in the global scope, just like the firstName and lastName
console.log (this.firstName + " " + this.lastName);
}
var person = {
firstName :"Penelope",
lastName :"Barrymore",
showFullName:function () {
// "this" on the line below refers to the person object, because the showFullName function will be invoked by person object.
console.log (this.firstName + " " + this.lastName);
}
}
showFullName (); // Peter Ally
// window is the object that all global variables and functions are defined on, hence:
window.showFullName (); // Peter Ally
// "this" inside the showFullName () method that is defined inside the person object still refers to the person object, hence:
person.showFullName (); // Penelope Barrymore
当包含this的回调函数做为参数传递时咱们会遇到这样这个问题:
// We have a simple object with a clickHandler method that we want to use when a button on the page is clicked
var user = {
name:"zhouquan",
age:21,
clickHandler:function (event) {
console.log (this.name + " " + this.age);
}
}
// The button is wrapped inside a jQuery $ wrapper, so it is now a jQuery object
// And the output will be undefined because there is no data property on the button object
$("button").click (user.clickHandler); //undefined
在上面的代码中,咱们知道$(“button”)是一个对象,”user.clickHandler”做为click()方法的回调函数。user.clickHandler方法中的this再也不是指向user对象,它如今指向的是调用点击事件的这个button对象。即便咱们是使用“user.clickHandler”来调用clickHandler方法,可是clickHandler()方法是在button对象做为上下文(Context)的环境中运行的,因此,this指向的是button对象。
从这一点上咱们能够看出,当上下文(Context)改变--当咱们在其余的对象上执行一个方法。“this”所指向的不在是之前的那个对象,而是如今调用这个方法的新的对象。
为了解决这个问题,咱们可使用apply, call和bind的方法来指定“this”所指向的对象。因此上面代码的最后一行只需改成:
$("button").click (user.clickHandler.bind (user)); //zhouquan 21
另一种容易让咱们感到困扰的是当咱们使用了一个内部函数(闭包)的时候。首先咱们应该明确的一点就是:闭包中不能经过“this”关键字来访问外边函数的this变量,由于闭包中的this他指向的window对象。来看一个例子:
var user = {
country: "china",
data:[
{name:"ZhouYi", age:21},
{name:"ZhouEr", age:22}
],
clickHandler:function(){
//在这个做用域中使用this是OK的,他指向的是user对象
this.data.forEach(function(person){
//可是这个内部函数的this再也不指向user对象
console.log("What is This referring to? " + this); //Object Window
console.log(person.name + " is come from " + this.country);
//ZhouYi is come from undefined
//ZhouEr is come from undefined
})
}
};
user.clickHandler();
clickHandler:function(){
//在这个做用域中使用this是OK的,他指向的是user对象
//咱们定义一个theUserObj来保存this的值
var theUserObj = this;
this.data.forEach(function(person){
//如今咱们再用theUserObj来访问user对象的属性就没问题了
console.log(person.name + " is come from " + theUserObj.country);
//ZhouYi is come from china
//ZhouEr is come from china
})
}
当咱们把一个对象里面的函数做为参数传递给另一个对象时,this所指定的对象每每会超出咱们的想象,来看个例子吧:
var data = [
{name: "ZhouYi", age:21},
{name: "ZhouEr", age:22}
];
var user = {
//这里的data属性是属于user对象的
data :[
{name:"ZhouYi", age: 31},
{name:"ZhouEr", age: 32}
],
showData:function(){
console.log(this.data[0].name + " " + this.data[0].age) ;
}
}
//把user.showData赋值给一个变量
var showUserData = user.showData;
//当咱们执行这个showUserData函数时,输出的数据来自全局的data(最外层定义的),而不是来自与user对象中的data.
showUserData(); //ZhouYi 21
解决这个问题的方式跟前面提到的解决回调函数中的this问题相似,咱们仍是采用apply, call和bind的方法来绑定指定的上下文,也就是this该指向哪一个对象。
var showUserDate = user.showData.bind(user);
何谓方法调用?打个简单的比方,有两个对象A和B,A、B有相同的属性,可是B比A还多了一个方法,这个方法是对B中的数据进行处理,如今咱们想把B这种方法也给A用用:
var gameController = {
scores : [20, 34, 55, 46, 77],
avgScore: null,
players:[
{name:"Tommy", playerID:987, age:23},
{name:"Pau", playerID: 87, age: 33}
]
}
var appController = {
scores: [900, 845, 809, 950],
avgScore: null,
avg: function(){
var sumOfSores = this.scores.reduce(function(prev, cur, index, array){
return prev + cur;
});
this.avgScore = sumOfSores /this.scores.length;
}
}
//因为avg()是被appController调用的,因此avg中的this指向的是appController对象。
gameController.avgScore = appController.avg();
console.log(gameController.avgScore); //undefined
如何解决这个问题呢? 为了让appController.avg()指向gameController对象,咱们可使用apply()方法:
// Note that we are using the apply () method, so the 2nd argument has to be an array—the arguments to pass to the appController.avg () method.
appController.avg.apply (gameController, gameController.scores);
// The avgScore property was successfully set on the gameController object, even though we borrowed the avg () method from the appController object
console.log (gameController.avgScore); // 46.4
// appController.avgScore is still null; it was not updated, only gameController.avgScore was updated
console.log (appController.avgScore); // null
注意咱们这里使用了两个参数,第一个参数表示this的上下文,也就是this所指向的对象;第二个参数表示要进行运算的数据。固然啦,咱们还能够经过这种方式达到一样的效果:
gameController.avg = appController.avg;
gameController.avg();
但愿我写的这些东西能够给你带来一些帮助,若是你以为哪一个地方存在不足,请你在评论处提出来,我将及时完善,省得误导后面的同窗;若是你以为这篇文章讲得还能够,请帮我推荐给更多的有须要的同窗阅读,谢谢!
参考资料:http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/