Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thomasjao/606cb65b1b2fcbeadf78 to your computer and use it in GitHub Desktop.
Save thomasjao/606cb65b1b2fcbeadf78 to your computer and use it in GitHub Desktop.
JavaScript in-depth
// 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 );
};
}
@thomasjao
Copy link
Author

建立 JavaScript 物件

建立 JavaScript 物件有三種方法:

  • 使用 new Object()
  • 使用 Object.create()
  • 使用 literal notation

前兩者都需先以定義一 function,再以特定的方式呼叫此 function 來 "初始化" 物件

JS 的命名慣例

一般作為定義物件 (相對於一般的 utility function) 的 function,其命名習慣以名稱首字母大寫。 例如

function Member() { 
    return { /* Lots of properties */ }
} 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment