LESSON 5 - Object 物件
// 沒有任何初始值的物件
var obj = {}; // 或者 var obj = new Object();
// 有初始值的物件
var obj = {
key: value
...
...
...
}
// 物件value可以是屬性(properties),
// 也可以是方法(function)
var car = {
name: "ferrari", // 字串
color: "red",
price: 100000, // 數字
extra: ["extra info 1", "extra info 2"], // 陣列
start: function() {},
drive: function() {},
stop: function() {}
};
OBJECT = car
KEY = name
VALUE = ferrari
Object Properties
// 物件
var car = {
name: "ferrari", --> 屬性
color: "red", --> 屬性
price: 100000, --> 屬性
extra: ["extra info 1", "extra info 2"], --> 屬性
start: function() {},
drive: function() {},
stop: function() {}
};
// 物件
var car = {
name: "ferrari",
color: "red",
price: 100000,
extra: ["extra info 1", "extra info 2"],
start: function() {}, --> 方法
drive: function() {}, --> 方法
stop: function() {} --> 方法
};
// 有兩種方式可以存取物件
var someObj = {
a: 'prop a',
b: 'prop b'
};
// 讀取
console.log(someObj.a); // 'prop a'
console.log(someObj['a']); // 'prop a'
console.log(someObj[a]); // a undefined
// 新增值
someObj.c = 'new val'; // or someObj['c'] = 'new val'
console.log(someObj.c); // 'new val'
// 改變值
someObj.a = 'new prop a'; // or someObj['a'] = 'new prop a'
console.log(someObj.a); // 'new prop a'
var person = {
firstName: 'Shi Yuan',
lastName: 'Wang',
age: 25,
fullName: function() {
return this.lastName + ' ' + this.firstName;
}
}
console.log('Hello' + person.fullName()); // Hello Wang Shi Yuan
console.log(person.fullName); // 印出function的描述
// 在這個例子中
// this參考的是person這個物件
// 因此在fullName這個function裏可以直接用this取得物件的屬性
var person = {
firstName: 'Shi Yuan',
lastName: 'Wang',
age: 25,
fullName: function() {
return this.lastName + ' ' + this.firstName;
}
}
this是一個javascript的特殊字元
在物件世界裏會作為上一層物件的參考
var person = {
firstName: 'Shi Yuan',
lastName: 'Wang',
age: 25,
fullName: function() {
return this.lastName + ' ' + this.firstName;
}
}
// 透過迴圈存取物件的值
for (var key in person) {
console.log(key + '的值為' + person[key]);
}
// 第一個人
var person1 = {
firstName: 'Shi Yuan',
lastName: 'Wang',
age: 25,
fullName: function() {
return this.lastName + ' ' + this.firstName;
}
}
// 第二個人
var person2 = {
firstName: 'Li',
lastName: 'Hu',
age: 21,
fullName: function() {
return this.lastName + ' ' + this.firstName;
}
}
// 把物件存到陣列裏
var persons = [person1, person2];
// 透過迴圈讀取值
for (var index in persons) {
var whichName = persons[index].fullName();
console.log('陣列的第'+ index + '個名字是' +whichName);
}
Constructor Function
function Person(lastName, firstName, age) {
this.lastName = lastName;
this.firstName = firstName;
this.age = age;
this.createdTime = new Date(), // 記錄當下時間
this.fullName = function() {
return this.lastName + ' ' + this.firstName;
}
}
var p1 = new Person('Wang', 'Shi Yuan', 25);
var p2 = new Person('Hu', 'Li', 21);
console.log('p1全名', p1.fullName());
console.log('p2全名', p2.fullName());
1. 宣告一個名為employee的物件, 此物件必須滿足一下條件
2. 設計一個簡單的侯位機制
Output:
第1位是{name},登記時間為{createdTime}
第2位是{name},登記時間為{createdTime}
......