javascript scope chain

來源:互聯網
上載者:User

標籤:javascript   scope   chain   

scope chain

一個函數有一個scope chain
函數每調用一次,該函數的scope上建立一個對象,函數的局部變數被當做屬性賦值給這個新對象。
所以對嵌套函數

function A() {    var a = ‘A‘;    function B() {        var b = ‘B‘    }    function C() {        var c = ‘C‘    }}

scope A <— scope B
^
|
|_ scope C
當A()被調用。 scope A上有新對象,新對象有a屬性。
scope B上有新對象, 新對象有b屬性。
scope C上有新對象, 新對象有c屬性。
B函數內能通過scope chain找到a 屬性
C函數也能通過scope chain找到a 屬性,兩者是同一對象。因為都是在A()的這次調用裡建立的對象的a屬性。

context上下文

阿里前端的一道題:

var Obj = function() {    this.msg = ‘ok‘;    this.shout = function() {        alert(this.msg)    };    this.waitAndShout = function() {        //填寫代碼,5s後調用this.shout    }}

錯誤碼1:

setTimeout.call(this, this.shout, 1000)// illegal invocation

錯誤碼2:

var f = setTimeout.bind(this)f(this.shout , 1000)// illegal invocation

正確代碼:

setTimeout( this.shout.bind(this) , 1000)// this.shout的context由window變為this
函數調用時,發生了什麼

函數被調用時,將建立一個execution context,建立執行內容時,發生了三件事:
1. 建立Activation object
2. 建立arguments 對象
3. 建立scope

這裡我們主要關心scope, scope是a list( or a chain ) of objects. 每個函數對象都有一個[[scope]]屬性,[[scope]]屬性由對象序列or對象鏈表構成。這個列表/鏈表被[[scope]]屬性引用,Activation object在列表/鏈表頭。
接下來,初始化variables. 也是發生三件事:
1. 函數的參數會變成Activation object的屬性。
2. 內建函式會變成Activation object的屬性。
3. var 會變成Activation object的屬性。

這些屬性都會賦值為undefined,直到執行函數體裡的指派陳述式。這就是傳說中的Hoisting, 預聲明~

scope呢?先看原文:

Function objects created with the Function constructor always have a [[scope]] property referring to a scope chain that only contains the global object.
Function objects created with function declarations or function expressions have the scope chain of the execution context in which they are created assigned to their internal [[scope]] property.

通俗翻譯一下:
1. 函數語句聲明的函數,[[scope]]指向global object
2. 函數定義和函數運算式的聲明的函數,[[scope]]指向他們執行內容的[[scope]]

Identifier Resolution:
解析標識符時,沿著[[scope]]指向的scope chain找,第一項顯然是Activition Object,裡麵包含了:參數,內建函式,內部變數。找不到標識付,再去第二項,也就是執行內容的[[scope]]找。。。依次類推。

所以之前A中含B,C的栗子,B,C的[[scope]]都指向了A的[[scope]],A的scope chain第一項含有a, 所以B,C都找到a,且是同一個a。

javascript scope chain

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.