创建对象的四种方式
- 1.字面量创建对象
- 2.工厂模式(即函数)创建对象
- 3.构造函数创建对象
- 4.class类创建对象
// 1.字面量创建对象
let Person = {
name: "Andy",
age: 18,
say: function () {
console.log("hello!");
},
};
console.log(Person);
console.log(Person.say());
// 2.工厂模式(即函数)创建对象
function person(name, age) {
return {
name: name,
age: age,
say: function () {
console.log("hello");
},
};
}
let student = person("Andy", 19);
console.log(student);
student.say();
// 3.构造函数创建对象
function Person(name, age) {
this.name = name;
this.age = age;
}
// 方法放到原型对象中,节省内存
Person.prototype.say = function () {
console.log("hello");
};
let student = new Person("Andy", 19);
console.log(student);
student.say();
// 4.class类创建对象
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
say() {
console.log("hello");
}
}
let student = new Person("Andy", 19);
console.log(student);
student.say();