- global context 中的 this global context 中的 this 指向 global object, 若在瀏覽器中執行 this 指向 window 物件
- 一般函式中的 this 當我們使用 function func1(){} 的方式宣告函數時, 函數的擁有者是 global object, 所以 this 指向 global object
- 巢狀函式(nested function) 中的 this
- 參數傳遞
- closure
- call & apply 中的 this 在JavaScript中,函式是Function的實例,Function 中有 call & apply function,可以讓使用者決定this的參考對象
- constructor 中的 this 若將函式當作建構式來用,內部的 this 則指向 new 所產生的新物件
console.log(this === window);//true
function func1() { return this; }
var obj = { func1 : func1 };//建立物件與函式的連結
obj.func1 === this.func1;//true
obj.func1() === obj;//函式內的 this 指向呼叫該函式的物件
func1() === this;//指向 global object
func1() === window;//true
function func2() {
function func3() {
return this;
}
return func3();
}
var obj = { func2 : func2 };
func2() === this;//true
obj.func2() === obj;//false
obj.func2() === this;//true
使用巢狀函式被呼叫時,this 是指向 global object, 這是要特別留意的地方,如果 func3 想取得 func2 的 this,可利用參數傳遞或 closure 的方式解決var obj = {
func2: function() {
function func3(that) {
return that;
}
return func3(this);
}
}
obj.func2() === obj;//true
var obj = {
func2: function() {
var that = this;
function func3() {
return that;
}
return func3();
}
}
obj.func2() === obj;//true
var o1 = {};
var o2 = {};
function func4() { return this; }
func4.call(o1) === o1; //true
func4.apply(o2) == o2;//true
複習一下 call 和 apply 的差別,兩者的差別在於傳遞參數的方法不同call是一個一個指定參數, examlple :
func.call(obj,"1","2","3")apply的第二個參數是陣列, examlple :
func.apply(obj,["1", "2", "3"])
function Employee(name, department) {
this.name = name;
this.department = department;
}
var e1 = new Employee('Albert', 'accounting');
console.log(e1.name);
利用 new 運算子建立物件,類似於下面的寫法
var e1 = (function(){
var _new = { constructor: Employee, __proto__: Employee.prototype };
_new.constructor();
return _new;
})();
如果對 prototype 的用法不熟悉可參考 Javascript Prototype Chain
0 comments:
Post a Comment