在 JavaScript 中,幾乎所有事物都可以視為物件。字串、數字、陣列、函式等都有物件特性。物件本質上是帶有屬性與方法的資料結構。
屬性是物件相關的值,方法是可以在物件上執行的操作。
const message = 'Hello World!';
console.log(message.length);
console.log(message.toUpperCase());
可以使用 new Object(),也可以使用物件字面值:
const person = new Object();
person.firstname = 'John';
person.lastname = 'Doe';
person.age = 50;
const person2 = {
firstname: 'John',
lastname: 'Doe',
age: 50,
eyecolor: 'blue'
};
若需要建立多個類似物件,可以使用建構函式:
function Person(firstname, lastname, age, eyecolor) {
this.firstname = firstname;
this.lastname = lastname;
this.age = age;
this.eyecolor = eyecolor;
this.changeName = function (name) {
this.lastname = name;
};
}
const myFather = new Person('John', 'Doe', 50, 'blue');
myFather.changeName('Smith');
在 JavaScript 中,this 通常指向目前執行的函式所屬物件。透過建構函式與 this,可以讓每個實例擁有自己的屬性與方法。