JavaScript 考題 3

Meow Meow Picture

目錄


物件

  • 物件的基本運作
  • 純值與物件的差異
  • 物件的參考特性

原始碼是否正確呢?

var person = {
name: '小明',
age: 32,
1: '2',
gender: 'male',
interests: ['吃飯', '睡覺', '打動動'],
greeting: function() {
console.log("Hi! I'm " + this.name[0] + '.');
},
哈囉: function() {
console.log('我是' + this.name);
}
};

解答:

  • 正確
  • 屬性都是字串
  • 屬性都是唯一的
// 如何取得上述的所有屬性值

person.name
person.age
person.gender
person.interests
person.greeting()

person.1 // Uncaught SyntaxError: Unexpected number
person[1]
person['1']

person[哈囉] // Uncaught ReferenceError: 哈囉 is not defined
person.哈囉
person.哈囉()
person['哈囉']()

純值與物件的差異

物件可以自由擴增 “屬性”,純值則無法。


範例程式碼

function callName() {
console.log('呼叫小明');
}
callName.ming = '小明';

測驗:請問結果為?

var a = 1;
a.a = 2;
console.log(a.a);
  1. 1
  2. 2
  3. undefined
  4. error

測驗:請問結果為?

var a = new Number(1);
a.a = 2;
console.log(a.a)
  1. 1
  2. 2
  3. undefined

測驗:請問結果為?

function fn() {
return 1;
}
fn.return = 2;
console.log(fn.return);
  1. 1
  2. 2
  3. undefined

測驗:請問結果為?

var a = 1;
function fn() {
a = fn.a;
}
fn.a = 2;
console.log(a);
  1. 1
  2. 2
  3. undefined

範例程式碼:

var family = {
name: '小明家',
members: {
father: '老爸',
mom: '老媽',
ming: '小明'
},
};
var member = family.members;
// 問題 重新賦予值是否影響
member = {
ming: '大明'
};
// 問題 2 修改單一屬性是否有影響
member.ming = '杰倫';
var ming = family.members.ming;

測驗:請問結果為?

var a = {};
var b = { b: 'c' };
var c = { c: 'b' };
a[b.b] = 123;
a[c.c] = 456;
console.log(a['b']);
  1. 123
  2. 456
  3. undefined

補充

var a = {
'哈囉': 1,
}

var hello = '哈囉';

console.log(a[hello]); // 1

測驗:請問結果為?

var a = {};
var b = { key: 'b' };
var c = { key: 'c' };
a[b] = 123;
a[c] = 456;
console.log(a[b]);
  1. 123
  2. 456
  3. undefined
NOTE: 屬性都是 字串

解答:

String(b) // [object, object]

console.log(a) // { [object, object]: 456 }

測驗:請問結果為?

var prop = '1';
var obj = {
1: function() {
console.log('1');
},
prop: function() {
console.log('2');
}
};
obj[prop]();
  1. 1
  2. 2
  3. undefined
  4. error

測驗:請問結果為?

var a = {};
a.a = a;
console.log(a.a.a === a.a);
  1. true
  2. false
  3. error
NOTE: 重要觀念題!!!

測驗:請問結果為?

var a = { x: 1 };
var b = a;
a.x = a = { x: 2 };

console.log(a);
console.log(b);
NOTE: 重要觀念題!!!

測驗:請問結果為?

var a = {};
var b = (a = {});
console.log(a === b);
  1. true
  2. false
  3. error
NOTE: 重要觀念題!!!

圖片來源: free background photos from pngtree.com