2012-12-22 18 views
0
// Situation 1 
var a = function A() { 
    this.x = 1; 
    var b = function B() { 
     this.x = 2; 
     console.log('Method B : x = ' + this.x); 
    }; 
    console.log('Method A : x = ' + this.x); 
    b(); 
} 

當我叫(),我的結果是「這個」,在函數調用的javascript

Method A : x = 1 
Method B : x = 2 

但如果我刪除 「this.x = 2」:

// Situation 2 
var a = function A() { 
    this.x = 1; 
    var b = function B() { 
     console.log('Method B : x = ' + this.x); 
    }; 
    console.log('Method A : x = ' + this.x); 
    b(); 
} 

我的結果將是

Method A : x = 1 
Method B : x = 1 

我不明白爲什麼

  • 在情況2: 「這」 函數B的被引用到的 「本」 功能的

但是

  • 在情況1:功能A的 「this.x」不改變時分配 「this.x = 2」,在函數B

我的代碼在Chrome V23運行

回答

2

因爲,this.x = 2是函數B的定義,直到B是稱爲它不會發生,而不是當它被定義。試試這個版本,看看:

// Situation 3 
var a = function A() { 
    this.x = 1; 
    var b = function B() { 
     this.x = 2; 
     console.log('Method B : x = ' + this.x); 
    }; 
    console.log('Method A before B: x = ' + this.x); 
    b(); 
    console.log('Method A after B: x = ' + this.x); 
} 
1

像你一樣調用b(),將導致this在瀏覽器環境中引用全局對象window)。

這也解釋了自己的行爲,your're書面方式基本上window.x = 1;

+0

我想當分配「var a = function A()」時,創建函數對象A()。然後,在函數A()中的「this」引用對象A,但我不明白爲什麼「this」引用__global對象_? –

2
  1. 原因this.x在兩個a被改變,b是因爲他們倆都引用window對象。

  2. 我想你對這個有誤解, this.x在致電b後被更改。我們可以看到這一點,如果我們扭轉電話:

    b(); // 2 
    console.log('Method A : x = ' + this.x); // 2 
    
1

你沒有打電話給b(),直到打印A的值之後。因此x的值是1,然後它被b更改爲2。

如果您在打印a()之前調用b()輸出將是

Method A : x = 2 
Method B : x = 2 

由於b()將第一個變化值,那麼a()將記錄

這是函數

var a = function A() { 
this.x = 1; 
var b = function B() { 
    this.x = 2; 
    console.log('Method B : x = ' + this.x); 
}; 
b(); 
    console.log('Method A : x = ' + this.x); 

} 

一個都b參考窗口對象window.x

0

this是在JavaScript中一個特殊的關鍵字,它依賴於上下文。在你的情況下,function B()function A()的上下文中。因此,如果您不覆蓋function B()中的this.x,它將成爲您在function A()中指定的值。