首页  >  文章  >  web前端  >  对象创建 - JavaScript 挑战

对象创建 - JavaScript 挑战

Susan Sarandon
Susan Sarandon原创
2024-11-03 14:33:31484浏览

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中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn