JS 对象创建的几种方式
第一种:Object 构造函数创建
const Person = new Object();
Person.name = 'Nike';
Person.age = 29;
这行代码创建了 Object 引用类型的一个新实例,然后把实例保存在变量 Person 中。
第二种:对象字面量
const Person = {}; // 等同于 new Object()
const Person = {
name: 'Nike',
age: 29
};
对象字面量是对象定义的简写形式,目的是简化包含大量属性的对象的创建过程。
第三种:工厂模式
function createPerson(name, age, job) {
const o = new Object();
o.name = name;
o.age = age;
o.job = job;
o.sayName = function () { alert(this.name); };
return o;
}
const person1 = createPerson('Nike', 29, 'teacher');
const person2 = createPerson('Arvin', 20, 'student');
工厂模式的问题:返回的都是 Object,无法用 instanceof 识别对象的具体类型。
第四种:构造函数模式
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
this.sayName = function () { alert(this.name); };
}
const person1 = new Person('Nike', 29, 'teacher');
相比工厂模式:
- 没有显式创建对象。
- 直接将属性和方法赋给了
this。 - 没有
return语句。 - 可以用
instanceof识别对象类型:
person1 instanceof Object; // true
person1 instanceof Person; // true
约定:构造函数始终以大写字母开头,普通函数以小写字母开头。
缺点:每个方法都在每个实例上重新创建一遍,方法多了会浪费内存。
第五种:原型模式
function Person() {}
Person.prototype.name = 'Nike';
Person.prototype.age = 20;
Person.prototype.job = 'teacher';
Person.prototype.sayName = function () { alert(this.name); };
const person1 = new Person();
person1.sayName();
原型模式让所有对象实例共享它所包含的属性和方法。
实例属性会屏蔽原型上的同名属性:
const person2 = new Person();
person1.name = 'Greg';
console.log(person1.name); // 'Greg'(实例)
console.log(person2.name); // 'Nike'(原型)
第六种:组合模式(构造函数 + 原型)—— 最常用
构造函数定义实例属性,原型定义方法和共享属性:
function Person(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
Person.prototype = {
constructor: Person,
sayName: function () { alert(this.name); }
};
const person1 = new Person('Nike', 20, 'teacher');
ES6 Class(语法糖)
class Person {
constructor(name, age, job) {
this.name = name;
this.age = age;
this.job = job;
}
sayName() {
alert(this.name);
}
}
const person1 = new Person('Nike', 20, 'teacher');
来源整理自:我的有道云笔记



