
You can find all the code in this post at repo Github.
Object creation methods
Constructor-based
Recommend before ES6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
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}`);
};
}
const person1 = new Person( "John" , "Doe" , 30);
person1.greet();
const person2 = new Person( "Jane" , "Smith" , 25);
person2.greet();
|
Copy after login
Class-based
Recommend after ES6.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | 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}`);
}
}
const person1 = new Person( "John" , "Doe" , 30);
person1.greet();
const person2 = new Person( "Jane" , "Smith" , 25);
person2.greet();
|
Copy after login
Object initializer
1 2 3 4 5 6 7 8 9 10 | const person = {
firstName: "John" ,
lastName: "Doe" ,
age: 30,
greet: function () {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
},
};
person.greet();
|
Copy after login
Object.create()
1 2 3 4 5 6 7 8 9 10 11 12 | 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" ;
person.greet();
|
Copy after login
Factory Pattern
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 |
function createPerson(firstName, lastName, age) {
return {
firstName: firstName,
lastName: lastName,
age: age,
greet: function () {
console.log(`Hello, my name is ${this.firstName} ${this.lastName}`);
},
};
}
const person1 = createPerson( "John" , "Doe" , 30);
person1.greet();
const person2 = createPerson( "Jane" , "Smith" , 25);
person2.greet();
|
Copy after login
Reference
- Classes - MDN
- Object-oriented programming - MDN
- Object-oriented programming - MDN
- Object initializer - MDN
- Object.create() - MDN
- Factory Pattern - patterns.dev
The above is the detailed content of Object creation - JavaScript Challenges. For more information, please follow other related articles on the PHP Chinese website!