標籤:javascript
JavaScript中的this關鍵字
JavaScript函數中的關鍵字this並不指其本身(Itself),舉例說明:
function foo(num) { console.log( "foo: " + num ); // keep track of how many times `foo` is called this.count++;}foo.count = 0;var i;for (i=0; i<10; i++) { if (i > 5) { foo( i ); }}// foo: 6// foo: 7// foo: 8// foo: 9// how many times was `foo` called?console.log( foo.count ); // 0
上例中儘管foo()執行了4次,但是foo.count依然為0,說明this指代的並不是foo函數自身。那麼我們執行的count++到底是給什麼值在增加呢?實際上我們建立了一個全域變數count,即window下的一個變數,其初始值為NaN,即使其被增加了4次,其值依然為NaN。
若上述樣本改為下面就很容易理解:
function foo(num) { console.log( "foo: " + num ); // keep track of how many times `foo` is called data.count++;}var data = { count: 0};var i;for (i=0; i<10; i++) { if (i > 5) { foo( i ); }}// foo: 6// foo: 7// foo: 8// foo: 9// how many times was `foo` called?console.log( data.count ); // 4
但是這裡,我們並沒有用到this關鍵字,我們只是選擇性地迴避了this,採用了另一種方式-Lexical scope來完成的。
如果我們要在函數內部引用其自身時,我們只能採用lexical identifier (variable)來指向其自身,如下:
function foo() { foo.count = 4; // `foo` refers to itself}
此種方式對於有函數名的函數有效,但是對於匿名函數就無能為力了,比如下面:
setTimeout( function(){ // anonymous function (no name), cannot // refer to itself}, 10 );
對此我們無能為力,不過有一個並不建議使用(目前已廢棄的方式)的方式來引用函數自身:arguments.callee,實際上我們最好的方式就是在需要引用函數自身時不要使用匿名函數,這樣就避免了上述問題的出現。
所以我們最開始時如果我們要引用自身函數時,採用其自身的函數名(identifier )即可:
function foo(num) { console.log( "foo: " + num ); // keep track of how many times `foo` is called foo.count++;}foo.count = 0;var i;for (i=0; i<10; i++) { if (i > 5) { foo( i ); }}// foo: 6// foo: 7// foo: 8// foo: 9// how many times was `foo` called?console.log( foo.count ); // 4
上例中我們似乎還是迴避了this關鍵字,只不過上例中我們要引用函數自身,不能使用this關鍵字。
如果我們一定要使用this關鍵字來指代函數自身時,我們可以這樣做:
function foo(num) { console.log( "foo: " + num ); // keep track of how many times `foo` is called // Note: `this` IS actually `foo` now, based on // how `foo` is called (see below) this.count++;}foo.count = 0;var i;for (i=0; i<10; i++) { if (i > 5) { // using `call(..)`, we ensure the `this` // points at the function object (`foo`) itself foo.call( foo, i ); }}// foo: 6// foo: 7// foo: 8// foo: 9// how many times was `foo` called?console.log( foo.count ); // 4
另一個對於this的誤解是指:this指的是函數的lexical scope,You Dont Know JS 中關於this有這樣的一段話:
To be clear, this does not, in any way, refer to a function’s lexical scope. It is true that internally, scope is kind of like an object with properties for each of the available identifiers. But the scope “object” is not accessible to JavaScript code. It’s an inner part of the Engine’s implementation.
請看下例:
function foo() { var a = 2; this.bar();}function bar() { console.log( this.a );}foo(); //undefined
上述代碼試圖通過this在foo()和bar()的lexical scopes中建立橋樑,所以通過bar()來擷取foo()的inner scope的變數a,這樣的橋樑實際上並不存在。
那麼this機制到底是怎樣的呢?其實,this是在運行時綁定的(runtime binding),而不是建立時綁定(author-time binding),即函數在調用時是基於其上下文來綁定的。
You Dont Know JS 中關於this機制有這樣的一段話:
‘This’ is not an author-time binding but a runtime binding. It is contextual based on the conditions of the function’s invocation. this binding has nothing to do with where a function is declared, but has instead everything to do with the manner in which the function is called.
When a function is invoked, an activation record, otherwise known as an execution context, is created. This record contains information about where the function was called from (the call-stack), how the function was invoked, what parameters were passed, etc. One of the properties of this record is the this reference which will be used for the duration of that function’s execution.
上述提到,this是在函數調用時基於其Call-site來綁定的,那麼什麼是Call-site呢
call-site: the location in code where a function is called (not where it’s declared).
那麼如何確定函數的call-site呢,
go locate where a function is called from
但是,確定函數的call-site並不容易,因此我們換一種思路,來尋找函數的call-stack:
the stack of functions that have been called to get us to the current moment in execution
下面我們來通過例子來說明call-site和call-stack的關係:
function baz() { // call-stack is: `baz` // so, our call-site is in the global scope console.log( "baz" ); bar(); // <-- call-site for `bar`}function bar() { // call-stack is: `baz` -> `bar` // so, our call-site is in `baz` console.log( "bar" ); foo(); // <-- call-site for `foo`}function foo() { // call-stack is: `baz` -> `bar` -> `foo` // so, our call-site is in `bar` console.log( "foo" );}baz(); // <-- call-site for `baz`
我們可以通過瀏覽器的dev Tool的debugger來調試查看函數的call-stack。
在我們清楚 call-site之後,我們來看this綁定的四條準則:
1. Default Binding
這條是最常見的綁定規則,也就是說this指向global object,請看例子:
function foo() { console.log( this.a );}var a = 2;foo(); // 2
如果在strict mode下,this指向undefined:
function foo() { "use strict"; console.log( this.a );}var a = 2;foo(); // TypeError: `this` is `undefined`
其中,一個細節要注意,如果foo()不是在strict mode下,其this仍指向global object:
function foo() { console.log( this.a );}var a = 2;(function(){ "use strict"; foo(); // 2})();
2. Implicit Binding
does the call-site have a context object, also referred to as an owning or containing object
如果call-site有內容物件,或者說其有包含它的容器物件,那麼此時Implicit Binding起作用了,看下例:
function foo() { console.log( this.a );}var obj = { a: 2, foo: foo};obj.foo(); // 2
上例中foo先被申明,然後被obj引用,實際上,即使在obj中申明函數,結果也一樣:
var obj = { a: 2, foo: function() { console.log( this.a ); }};obj.foo(); // 2
call-site uses the obj context to reference the function, so you could say that the obj object “owns” or “contains” the function reference at the time the function is called.
obj在foo()函數被調用之前持有foo函數的引用,即obj是foo的內容物件,此時Implicit Binding生效,this也就指向了該內容物件。注意下面的一種情況:
function foo() { console.log( this.a );}var obj2 = { a: 42, foo: foo};var obj1 = { a: 2, obj2: obj2};obj1.obj2.foo(); // 42
思考下面的樣本:
function foo() { console.log( this.a );}var obj = { a: 2, foo: foo};var bar = obj.foo; // function reference/alias!var a = "oops, global"; // `a` also property on global objectbar(); // "oops, global"
表面上看,bar是通過obj的foo屬性來指向foo函數的,實際上,bar是直接指向foo的引用的,因為obj中的foo也是指向foo引用的。此時,因為this就失去綁定,default binding生效。
function foo() { console.log( this.a );}function doFoo(fn) { // `fn` is just another reference to `foo` fn(); // <-- call-site!}var obj = { a: 2, foo: foo};var a = "oops, global"; // `a` also property on global objectdoFoo( obj.foo ); // "oops, global"
這裡,我們通過參數傳遞將foo函數引用賦值給fn,此時就與obj無關了,是fn指向foo函數引用了,this失去隱式綁定,default binding生效,即使你傳入回呼函數(即這裡的fn)的函數不是自己寫的也沒有關係:
function foo() { console.log( this.a );}var obj = { a: 2, foo: foo};var a = "oops, global"; // `a` also property on global objectsetTimeout( obj.foo, 100 ); // "oops, global"
這裡的setTimeout我們可以這樣理解:
function setTimeout(fn,delay) { // wait (somehow) for `delay` milliseconds fn(); // <-- call-site!}
這樣與上文就一致了。
著作權聲明:本文為博主原創文章,未經博主允許不得轉載。
JavaScript中的this關鍵字