首頁 > web前端 > js教程 > 主體

物件創建 - JavaScript 挑戰

Susan Sarandon
發布: 2024-11-03 14:33:31
原創
490 人瀏覽過

Object creation - JavaScript Challenges

您可以在 repo Github 上找到這篇文章中的所有程式碼。


物件建立方法


基於構造函數

ES6之前推薦。

/**
 * @param {string} firstName
 * @param {string} lastName
 * @param {number} age
 */

function Person(firstName, lastName, age) {
  this.firstName = firstName;
  this.lastName = lastName;
  this.age = age;
  this.greet = function () {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
  };
}

// Usage example
const person1 = new Person("John", "Doe", 30);
person1.greet(); // => Hello, my name is John Doe

const person2 = new Person("Jane", "Smith", 25);
person2.greet(); // => Hello, my name is Jane Smith
登入後複製

基於類別

ES6 之後推薦。

class Person {
  constructor(firstName, lastName, age) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
  }
}

// Usage example
const person1 = new Person("John", "Doe", 30);
person1.greet(); // => 'Hello, my name is John Doe'

const person2 = new Person("Jane", "Smith", 25);
person2.greet(); // => 'Hello, my name is Jane Smith'
登入後複製

物件初始值設定項

const person = {
  firstName: "John",
  lastName: "Doe",
  age: 30,
  greet: function () {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
  },
};

person.greet(); // => 'Hello, my name is John Doe'
登入後複製

對象.create()

const personPrototype = {
  greet: function () {
    console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
  },
};

const person = Object.create(personPrototype);
person.firstName = "John";
person.lastName = "Doe";

// Usage example
person.greet(); // => 'Hello, my name is John Doe'
登入後複製

工廠模式

/**
 * @param {string} firstName
 * @param {string} lastName
 * @param {number} age
 * @return {object}
 */

function createPerson(firstName, lastName, age) {
  return {
    firstName: firstName,
    lastName: lastName,
    age: age,
    greet: function () {
      console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
    },
  };
}

// Usage example
const person1 = createPerson("John", "Doe", 30);
person1.greet(); // => 'Hello, my name is John Doe'

const person2 = createPerson("Jane", "Smith", 25);
person2.greet(); // => 'Hello, my name is Jane Smith'
登入後複製

參考

  • 類 - MDN
  • 物件導向程式設計 - MDN
  • 物件導向程式設計 - MDN
  • 物件初始值設定項 - MDN
  • Object.create() - MDN
  • 工廠模式-patterns.dev

以上是物件創建 - JavaScript 挑戰的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:dev.to
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
作者最新文章
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板