Just JavaScript_07: Properties

Properties

1
2
3
4
5
6
let sherlock = {
  surname: 'Holmes',
  age: 64,
};

console.log(sherlock.age); // 64

Assigning to a Property

1
sherlock.age = 65;

Missing Properties

1
2
let sherlock = { surname: 'Holmes', age: 64 };
console.log(sherlock.boat); // undefined

Note this does not mean that our object has a boat property pointing to undefined! It only has two properties, and neither of them is called boat:

Recap

  • Properties are wires — a bit like variables. They both point at values. Unlike variables, properties start from objects in our universe.

  • Properties have names. Properties belong to particular objects. You can’t have more than one property with the same name on an object.

  • Generally, you can perform an assignment in three steps:

    1. Figure out which wire is on the left.
    2. Figure out which value is on the right.
    3. Point that wire to that value.
  • An expression like obj.property is calculated in three steps:

    1. Figure out which value is on the left.
    2. If it’s null or undefined, throw an error.
    3. If that property exists, the result is the value its wire points to.
    4. If that property doesn’t exist, the result is undefined.

觀念小測驗

JJS: Properties

非常巧妙的例子:

1
2
3
4
5
6
7
8
9
let president = {
	name: 'Pooh',
	next: null
}

president.next = {
	name: 'Paddington',
	next: president
}

1
2
3
console.log(president.next.next.next.name); //?

// 答案:'Paddington'
  • 寫出下方概念的程式碼

1
2
3
4
let president = {
	name: 'Pooh',
}
president.next = president
最後更新 Mar 23, 2022 16:22 +0800