[JavaScript] JSDC 2013 白板題 - this
今年 JSDC 比去年相較之下與會的人變多了,各種前端技術的社群( Node, Angular, Front-end Developer) 不斷冒出來,反映有愈來愈多人想投入這領域,真心希望前端設計師在台灣可以愈來愈受重視!前端魂阿~
以上都是題外話,今日午茶時間,在攤位附近的白板上有出了幾個 JS 的題目,旁邊寫了"可以跟 David Shariff 討論",所以我想應該是 David 出的吧? 因為解的人實在太多了,所以只有看到最前面那一題,題目是:
這題如果沒有理解錯的話,是問如果呼叫了 boo 這個 method 時 x 等於多少?這題考的是 this 的觀念,對於熟悉 OO 的人來說 this 並不陌生,但有別於 classical 程式語言,JavaScript 的 this 是根據 invocation pattern 來決定的,因為 foo 是一個 object,因此呼叫其 boo 函式時,屬於 method invocation - this 會跟呼叫該 method 的物件綁定,因此回傳 this.x 值就是 foo 的 x 屬性 20。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var x = 10; | |
var foo = { | |
x: 20, | |
boo: function(){ | |
var x = 30; | |
return this.x; | |
} | |
}; | |
//what is x ? |
這題如果沒有理解錯的話,是問如果呼叫了 boo 這個 method 時 x 等於多少?這題考的是 this 的觀念,對於熟悉 OO 的人來說 this 並不陌生,但有別於 classical 程式語言,JavaScript 的 this 是根據 invocation pattern 來決定的,因為 foo 是一個 object,因此呼叫其 boo 函式時,屬於 method invocation - this 會跟呼叫該 method 的物件綁定,因此回傳 this.x 值就是 foo 的 x 屬性 20。
留言
張貼留言