javascript核心篇 - 物件 partI

javascript核心篇 - 物件 partI

最近在上六角學院的js核心篇,將筆記整理出來跟大家分享。

物件的宣告

(推薦)物件實字 Object Literals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
//value可以是純值, 原始型別, 函式或另一個物件
//屬性名稱一定要是字串, 應避免 0:1
var family = {
property: value,
name:'貓貓家',
deposit: 500,
members:{
big_cat:'大貓貓',
small_cat:'小貓貓'
},
food:['fish', 'dryFood'],
callFamily: function(){
console.log(this)
//這個family物件
},
callAgain: ()=>{
console.log(this)
//window物件
}

}

物件建構式

1
2
var newFamily = new Object(family)
newFamily == family //true

物件的取值、新增和刪除

  1. 取值

family.members
family[‘members’]
使用中括號不只可使用字串方式取值,可以用數字,也可以使用變數方式作取值,甚至在中括號中做運算後再取值

1
2
3
family['food'][0] //'fish'
let a = 0;
family.food[a] //'fish'
  1. 新增
1
2
3
4
//新增一個屬性叫pet, 值為hamster
family.pet='hamster'
//新增一個屬性叫mouse, 值為jerry
family["mouse"] = 'jerry'
  1. 刪除 delete
1
2
3
4
5
6
7
8
9
delete family.food
delete family['food']

//結果
name: "貓貓家"
deposit: 500
members: {big_cat: "大貓貓", small_cat: "小貓貓"}
callFamily: ƒ ()
callAgain: ƒ ()

變數與物件屬性的差異

變數無法被刪除,物件的屬性才可以

1
2
3
4
5
6
7
8
9
10
11
//此時a,b都存在在window物件下
//a為變數
var a = 1;
//b是window物件內的property
b=2;

delete a; //false
delete b; //true 可被刪除

console.log(a) //1 無法被刪除
console.log(b) //not defined (被刪除了)
Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×