以下示例是关于Javascript中包含在 JavaScript 中创建对象的 5 种方法用法的示例代码,想了解在 JavaScript 中创建对象的 5 种方法的具体用法?在 JavaScript 中创建对象的 5 种方法怎么用?在 JavaScript 中创建对象的 5 种方法使用的例子?那么可以参考以下相关源代码片段来学习它的具体使用方法。
// https://levelup.gitconnected.com/5-ways-to-create-an-object-in-javascript-55d556193ee8
// 1 . Object Literals
const car = {
make: 'Toyota',
model: 'Corolla',
year: 2021
};
console.log(car);
// 2. The new Object() Syntax
const person = new Object();
person.name = 'John';
person.age = 30;
person.isEmployed = true;
console.log(person);
// 3. Constructor Functions
function Smartphone(brand, model, year) {
this.brand = brand;
this.model = model;
this.year = year;
}
const myPhone = new Smartphone('Apple', 'iPhone 13', 2021);
console.log(myPhone);
// 4 The Object.create() Method
const animal = {
type: 'Animal',
displayType: function() {
console.log(this.type);
}
};
const dog = Object.create(animal);
dog.type = 'Dog';
dog.displayType(); // Output: Dog
// ES6 Class Syntax
class Book {
constructor(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
}
getSummary() {
return `${this.title} was written by ${this.author} in ${this.year}`;
}
}
const myBook = new Book('1984', 'George Orwell', 1949);
console.log(myBook.getSummary());
本文地址:https://www.itbaoku.cn/snippets/876623.html