1. 程式人生 > >理解javascript中this的指向(簡單理解篇)

理解javascript中this的指向(簡單理解篇)

先列舉幾種常用的this指向:

// 全域性下this=window
console.log(this==window);
this.a = 1;
console.log(window.a);

// 物件屬性上函式的this指向的是物件obj
var obj = {
a:1,
sayA:function(){
console.log(this.a);
}
};
obj.sayA();

// 通過物件呼叫方法,此時this指向物件teacher1、teacher2
var Teacher=function(property){
this.name = property.name;
this.sex = property.sex;
}
Teacher.prototype.say=function(){
console.log("我是一名老師,我的名字叫“"+this.name+"”,今年"+this.sex+"歲!")
};
var teacher1 = new Teacher({"name":"張三","sex":25});
var teacher2 = new Teacher({"name":"李四","sex":32});
teacher1.say();
teacher2.say();

// 還有很多種可能性我就不一一細說了,此篇文章只針對於較為簡單的this解釋。(其他的包括建構函式上的、get/set上的、call/apply中的、bind等等,有興趣可以自己瞭解一下)。

// 根據綜上所述得到一個總結(如有問題,勿噴):

函式中的this指向呼叫此函式的物件!(比如說上面的window、obj、teacher1/teacher2,此定義在自己封裝外掛的時候會用到,舉個簡單的例子easyui中combobox的onSelect回撥函式中this指向繫結此combobox的dom)。