2013-03-06 34 views
1

在書JavaScript Enlightenment(鏈接是一個預先發布的版本(第85頁),但我有已發佈的版本(第6.3章),它說同樣的事情),它說任何內部函數將把this視爲ECMA-3中的全局對象(window),但將在ECMA-5中修復。在JavaScript中,任何獨立的內部函數都將「this」當作原始方法被調用的對象嗎?

的代碼如下:

http://jsfiddle.net/javascriptenlightenment/9GJhu/

var myObject = { 
    func1: function() { 
     console.log(this); // logs myObject 
     var func2 = function() { 
      console.log(this) // logs window, and will do so from this point on 
      var func3 = function() { 
       console.log(this); // logs window, as it’s the head object 
      }(); 
     }(); 
    } 
} 

myObject.func1(); 

但我認爲目前的Chrome,Firefox和node.js中應實現ECMA-5在很大程度上,所以我嘗試以上代碼,他們仍然打印出func2func3中的全局對象。然後我將"use strict";加到func1,以防萬一,也加到func2func3。代碼:http://jsfiddle.net/9GJhu/6/現在在Chrome和node.js中,this將作爲undefined而不是myObject打印出來。所以根據這本書,在ECMA-5中this應該是myObject。上面的代碼有什麼問題?

回答

2

我可能是錯的,但我沒有看到規範中的任何地方。
按照ECMAScript 5.1 specification 10.4.3輸入功能代碼

  1. 如果函數代碼是嚴格代碼,則ThisBinding設置爲thisArg。
  2. 否則,如果thisArg爲null或未定義,請將ThisBinding設置爲全局對象。
  3. 否則,如果Type(thisArg)不是Object,請將ThisBinding設置爲ToObject(thisArg)。
  4. 否則將ThisBinding設置爲thisArg。
  5. 讓localEnv成爲調用NewDeclarativeEnvironment傳遞F的[[Scope]]內部屬性值作爲參數的結果。
  6. 將LexicalEnvironment設置爲localEnv。
  7. 將VariableEnvironment設置爲localEnv。
  8. 設代碼爲F的[[Code]]內部屬性的值。
  9. 使用10.5中描述的功能代碼和argumentsList執行聲明綁定實例化。

根據(1),因爲你的func2func3沒有任何背景,而你指定strict mode你的背景將被設定爲undefined。如果沒有strict mode並根據(2.)this將設置爲window

1

當您使用'use strict'指令時,默認情況下,'this'關鍵字是'undefined',與非嚴格模式相反,'this'關鍵字默認指向全局對象。您需要明確指定上下文。

在附註中,您只需要聲明'use strict'一次。

0

功能嵌套的事實並不意味着任何事情。他們繼續工作以同樣的方式還沒有嵌套:

var myObject = { 
    func1: function() { 
     console.log(this); // logs myObject 
    } 
} 
myObject.func1(); 

var func2 = function() { 
    console.log(this) // logs window, and will do so from this point on 
}(); 

var func3 = function() { 
    console.log(this); // logs window, as it’s the head object 
}(); 

http://jsfiddle.net/NYr3y/2/

var myObject = { 
    func1: function() { 
     "use strict"; 

     console.log(this); // logs myObject 
    } 
} 

myObject.func1(); 


var func2 = function() { 
    "use strict"; 

    console.log(this) // logs window, and will do so from this point on 

}(); 

var func3 = function() { 
    "use strict"; 

    console.log(this); // logs window, as it’s the head object 
}(); 

http://jsfiddle.net/4B84u/2/

第一個函數調用與上下文(作爲一種方法)等,然後「本」是myObject的。

其他函數在沒有上下文的情況下調用(就像func2()),在這種情況下,ECMA-5不允許通過這個明確引用全局對象。

大多數瀏覽器默認情況下不應用ECMA-5,因爲由於限制更多而不兼容追溯。

相關問題