Skip to main content

🍕JavaScript-创建对象的六种方式

·208 words·1 min
Yalois
Author
Yalois

创建对象
#

使用对象字面量
#

这是最常用的方法。

let person={
    name: "John",
    age: 20,
    greet: function() {
        console.log("Hello,my name is "+this.name);
    }
}

person.greet();
//输出Hello,my name is John

使用构造函数
#

定义一个构造函数,然后使用new关键字来创建对象。

function Person(name, age) {
  this.name = name;
  this.age = age;
  this.greet = function() {
    console.log("Hello, my name is " + this.name);
  };
}

// 创建对象
let john = new Person("John", 30);
john.greet(); // 输出: Hello, my name is John

使用 Object.create() 方法
#

代码来自: Object.create() - JavaScript | MDN (mozilla.org)

const person = {
  isHuman: false,
  printIntroduction: function () {
    console.log(`My name is ${this.name}. Am I human? ${this.isHuman}`);
  },
};

const me = Object.create(person);

me.name = 'Matthew'; // “name”是在“me”上设置的属性,不是在“person”上。
me.isHuman = true; // 覆盖继承的属性

me.printIntroduction();//输出> "My name is Matthew. Am I human? true"

使用 ES6 类
#

ES6 引入了类语法,使得定义和创建对象更加直观。

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

  greet() {
    console.log("Hello, my name is " + this.name);
  }
}

// 创建对象
let john = new Person("John", 30);
john.greet(); // 输出: Hello, my name is John

使用工厂函数
#

工厂函数是一种返回对象的普通函数。传入参数之后直接返回对象。

function createPerson(name, age) {
  return {
    name: name,
    age: age,
    greet: function() {
      console.log("Hello, my name is " + this.name);
    }
  };
}

// 创建对象
let john = createPerson("John", 30);
john.greet(); // 输出: Hello, my name is John