对象创建 - JavaScript 挑战

对象创建 - javascript 挑战

您可以在 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 挑战的详细内容,更多请关注其它相关文章!