Object and Function

傅勝華
3 min readAug 8, 2021

Object 是 key-value 形式的儲存格式,裏頭有放兩種東西 1.property (primitive and Object), 2.method (function)

myObj = {
one: 1,
two: {inner: 2},
three: function(){console.log(3)},
four: “four”}
分別是 1. property 2.property 3.method 4.property

object = {name: value} 是 object literal syntax。 {} 不是運算子,而是創造一個物件的意思

呼叫 object 的 value 有兩種方式,一種是用方括弧 [] ,裡頭放字串;另一種是用點元素 . ,後面加相對應的 name 。大多數時候用點元素即可,方括弧的使用時機是,當 name 是一個動態字串時使用 (可以理解為變數)。

有了 object 讓 JS 有了 fake namespace 的概念,把 object 當成 namespace 做使用
JSON (JavaScript Object Notation) 就是借用 object 格式(嚴格版)的資訊檔

function 即物件,所以物件能做的事,函數也能做,這引申了一個名詞 first class function 意思就是,函數能做其他型別能做的事,EX:當參數被傳入另一個函數。

function 被呼叫時會創造一個 Execution Context 因此也會有自己的 variable environment, this, outer environment ,一般情況下 this 都會指向 window ,但物件的函數 method 的 this 會指向物件本身,而 method 裏 function 的 this 又會指向 window。

myObj = {
a: funtion(){
console.log(this); =>myObj
function b(){
console.log(this);}
b(); =>window
}}

要解決這個問題,習慣在 method 設定時開頭加上 const self = this; 之後要選取物件本身時,都用變數 self 就好。

function 為物件,代表它也有自己的 property 和 method ,另外他多了兩個屬性,一個是 name 指 function 本身的名字 (可以是 anonymous 匿名函數);一個是 code 也就是你寫的程式碼,可以被 invoke 也就是被呼叫。

function 分 陳述式表示式 。陳述式是功能性函數,不會回傳值,EX:if(){};表示式是會回傳值的函數,EX:帶有 return 的函數、a = funtion(){} 函數本身會被當成值(物件)回傳給 變數a 。

另外有個概念 by value 和 by reference ,這是兩種不同的變數設定方式,當設定純值給變數時
let a = 3;
let b = a;
a = 4;
console.log(a); => 4
console.log(b); => 3
每個變數會有自己的空間,這叫 by value

let a = {name : value};
let b = a;
b.name = valueChanged;
console.log(a); => {name : valueChanged}
console.log(b);=> {name : valueChanged}
變數會指向同一個空間的物件,這叫 by reference

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

傅勝華
傅勝華

No responses yet

Write a response