🍕JavaScript-创建对象的六种方式
创建对象 使用对象字面量 这是最常用的方法。 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 引入了类语法,使得定义和创建对象更加直观。 ...