this:
在 JavaScript 中,上下文對象就是 this 指針,即被調(diào)用函數(shù)所處的環(huán)境。上下文對象 的作用是在一個(gè)函數(shù)內(nèi)部引用調(diào)用它的對象本身。在 JavaScript 中,本質(zhì)上,函數(shù)類型的變量是指向這個(gè)函數(shù)實(shí)體的一個(gè)引用,在引用之 間賦值不會(huì)對對象產(chǎn)生復(fù)制行為胖秒。我們可以通過函數(shù)的任何一個(gè)引用調(diào)用這個(gè)函數(shù),不同之 處僅僅在于執(zhí)行時(shí)候的上下文,可以通過bind,apply,call等改變this的指向。
function test() {
var obj = {
f: function() {
console.log(this === window)
}
}
return obj;
}
test().f() // 輸出 false 因?yàn)閒 執(zhí)行時(shí),是obj 的屬性
function test() {
var obj = {
f: function() {
console.log(this === window)
}
}
return obj.f;
}
test()() // 輸出 true test() 返回一個(gè)函數(shù)阶女,(其實(shí)返回的函數(shù)是由一個(gè)臨時(shí)變量應(yīng)用的,在window作用域)
改變this
var myObj = {
specialFunction: function () {
},
getAsyncData: function (cb) {
cb();
},
render: function () {
var that = this;
this.getAsyncData(function () {
that.specialFunction();
});
}
};
myObj.render();
或者render這樣寫
render: function () {
this.getAsyncData(function () {
this.specialFunction();
this.anotherSpecialFunction();
}.bind(this));
}
Function.prototype.bind = function (scope) {
var fn = this;
return function () {
return fn.apply(scope);
};
}
函數(shù)作用域
函數(shù)作用域的嵌套關(guān)系是定義時(shí)決定的,而不是調(diào)用時(shí)決定的,也就 是說,JavaScript 的作用域是靜態(tài)作用域,又叫詞法作用域,這是因?yàn)樽饔糜虻那短钻P(guān)系可 以在語法分析時(shí)確定,而不必等到運(yùn)行時(shí)確定
var a=1;
function test(){
var a=2;
return function(){
console.log(a)
}
}
test()(); // 輸出 2 閉包是(函數(shù)作用域的問題)