Print

如何在 JS 中创建对象?


作者: 文章来源:

本文原地址:https://www.mimiwuqi.com/webqianduan/197434.html

使用对象字面量:

const o = {
  name: "",
  greeting() {
    return `Hi, 我是${this.name}`;
  }
};

o.greeting(); // "Hi, 我是"

使用构造函数:

function Person(name) {
   this.name = name;
}

Person.prototype.greeting = function () {
   return `Hi, 我是${this.name}`;
}

const mark = new Person("");

mark.greeting(); // "Hi, 我是"

使用 Object.create 方法:

const n = {
   greeting() {
      return `Hi, 我是${this.name}`;
   }
};

const o = Object.create(n); 
o.name = "";

更多 建站教程 请访问 https://www.mimiwuqi.com/webqianduan/