Created
March 5, 2015 17:03
-
-
Save thomasjao/606cb65b1b2fcbeadf78 to your computer and use it in GitHub Desktop.
JavaScript in-depth
This file contains hidden or 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
// JavaScript In-Depth | |
JavaScript 的 function 是 first-class 的意義: | |
* function 可以被指派到某個變數 | |
* function 可以當作另一個 function 的參數 | |
* function 可以作為另一個 function 的回傳值 | |
* function 具備和 Object 一樣的特質,包括:high order(?), assign 及 property | |
Higher-order function 的意義:1. function 可以將 1 或多個 function 作為參數 2. 輸出(回傳) function | |
// 如何呼叫 JS function // | |
========================== | |
function hello( param1 ) { | |
console.log("Hello " + param1); | |
} | |
// this: | |
hello("world"); // "Hello world" | |
// desugars to: | |
hello.call( window, "world"); // "Hello world" | |
// Since ECMAScript 5 only when using strict mode | |
hello.call( undefined, "world"); // "Hello world" | |
// Imediately invoke | |
(function() {})() same as (function(){}).call(window|undefined) | |
// Using Function.prototype.bind // | |
=================================== | |
// 如何定義一物件 // | |
==================== | |
根據 John Resig 的說法,先定義一空物件,再以該物件的 prototype 定義其 property 遠快於直接定義 | |
// Very fast | |
function User() {} | |
User.prototype = { /* Lots of properties ... */ }; | |
// Very slow | |
function User() { | |
return { /* Lots of properties */ }; | |
} | |
// makeClass - By John Resig (MIT Licensed) | |
// URL: http://ejohn.org/blog/simple-class-instantiation/#postcomment | |
function makeClass(){ | |
return function(args){ | |
if ( this instanceof arguments.callee ) { | |
if ( typeof this.init == "function" ) | |
this.init.apply( this, args.callee ? args : arguments ); | |
} else | |
return new arguments.callee( arguments ); | |
}; | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
建立 JavaScript 物件
建立 JavaScript 物件有三種方法:
new Object()
Object.create()
前兩者都需先以定義一
function
,再以特定的方式呼叫此function
來 "初始化" 物件JS 的命名慣例
一般作為定義物件 (相對於一般的
utility function
) 的function
,其命名習慣以名稱首字母大寫。 例如