DIV CSS 佈局教程網

JavaScript 物件概念入門:屬性、方法與建構方式
編輯:JavaScript基礎知識     

在 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,可以讓每個實例擁有自己的屬性與方法。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved