前端工程

Some basics of JavaScript

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。

從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。

FB粉專會頻繁地更新 Larry 對於商業、社會、人生的觀察與心得,歡迎大家追蹤互動~

JS Objects
http://www.w3schools.com/js/js_object_definition.asp

# Three ways to create JS objects

  – Use object literal (like Python dictionaries)
  – Use “new Object()” (w3schools 建議使用 object literal 而不是 new object)
  – Use object constructor (use “function” to declare an OO like class constructor)

# Primitive data types vs objects

JS 有 3 種 primitive data types: string, number, boolean, 同時他們有 object version: String, Number, Boolean. w3schools 建議使用 primitive data types instead of object data types, because primitive data types are faster and have better reading simplicity.
沒有 primitive 只有 object 的 data types: Object, Array, RegExp, Function, 等. Again, w3schools 建議使用 literal instead of new.

另外 JS 很重要一點是 object is called by reference; primitive type is called by value. Note even for simple assignment, object is assigned by address.

primitive data type 的 typeof 就直接是 “string”, “number”, or “boolean”, object 的 typeof 一律是 “object”。因為要區分 called by reference/value, 在 JS 中要明確知道自己用的是 primitive data types 還是 objects.

# Modify properties of a prototype

Object property 可以被增加/更改 by

your_obj.your_prop = ooxx;

但這只能更改該 object 的 property, 要更改 object prototype 的 property 要用

obj_name.prototype.your_prop = ooxx;

需注意的是上面更改 prototype property/method 的方式會繼承到所有 objects。


# JS Functions
http://www.w3schools.com/js/js_function_definition.asp

1. Function declaration and expression

Function expression: stored in a variable, 稍後執行. 宣告的時候可以是 anonymous function (也可以不是). 通常是 anonymous function, 因為 assign 的變數已經有名稱了, function 不用 redundant naming.

2. Self-Invoking functions.

3. JS functions do not check the types and number of passed arguments. The built-in “arguments” object.

How about function overload? 搜尋了一下, JS 沒有 function overload 概念, 還是要去確認 input argument types. 另外 JavaScript 不確認 argument 的”型態”與”數量”, 那是否宣告 function 時都不用宣告參數, 直接用 “arguments” object? 搜尋了一下沒有明確的答案. 我覺得還是程式碼可讀性的問題, 宣告參數加 function 外部 comment, 會比用 “arguments” (即使一樣加comment) 漂亮, 比較容易讓 caller 端調用.

商業,創業,業務,職涯,美食,葡萄酒,閱讀,網路科技。

從 Larry 創業以及商業的經驗,希望以白話的口吻,介紹給大家這個商業的世界。

FB粉專會頻繁地更新 Larry 對於商業、社會、人生的觀察與心得,歡迎大家追蹤互動~

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *