官术网_书友最值得收藏!

Functions as objects

The concept of first-class objects means that functions can be created, assigned, changed, passed as parameters, or returned as result of yet other functions, in the very same way that you can do with, say, numbers or strings. Let's start with their definition. When you define a function in the usual way:

function xyzzy(...) { ... }

This is (almost) equivalent to writing:

var xyzzy = function(...) { ... }

Except for hoisting. JS moves all definitions to the top of the current scope, but not assignments; so, with the first definition you can invoke xyzzy(...) from any place in your code, but with the second you cannot invoke the function until the assignment has been executed.

See the parallel with the Colossal Cave Adventure Game? Invoking xyzzy(...) anywhere won't always work! And, if you never played that famous interactive fiction game, try it online -- for example, at http://www.web-adventures.org/cgi-bin/webfrotz?s=Adventure or http://www.amc.com/shows/halt-and-catch-fire/colossal-cave-adventure/landing.

The point we want to make, is that a function can be assigned to a variable -- and can also be reassigned, if desired. In a similar vein, we can define functions on the spot, when they are needed. We can even do this without naming them: as with common expressions, if used only once, then you don't need to name it or store it in a variable.

主站蜘蛛池模板: 噶尔县| 调兵山市| 重庆市| 新巴尔虎右旗| 九龙坡区| 耒阳市| 清新县| 舟山市| 绥化市| 阿鲁科尔沁旗| 平阳县| 叙永县| 定日县| 平果县| 青铜峡市| 济宁市| 石景山区| 安宁市| 镇宁| 商都县| 平陆县| 安泽县| 历史| 亚东县| 富锦市| 岱山县| 郧西县| 北安市| 游戏| 金寨县| 梁河县| 宁都县| 临高县| 灵石县| 广元市| 丰原市| 闽清县| 汉源县| 墨玉县| 洪雅县| 乌兰察布市|