Object函数构造模式
方式一: Object构造函数模式
套路: 先创建空Object对象, 再动态添加属性/方法
适用场景: 起始时不确定对象内部数据
问题: 语句太多
var ob = new Object();
ob = {};
ob.name = "凌月";
ob.age = 18;
ob.setName = function (name) {
name = this.name;
}
ob.setAge = function (age) {
age = this.age;
}
ob.name="凤千羽";
ob.age=22;
console.log(ob.name,ob.age);
对象字面量
方式二: 对象字面量模式
套路: 使用{}创建对象, 同时指定属性/方法
适用场景: 起始时对象内部数据是确定的
问题: 如果创建多个对象, 有重复代码
var ob={
name : "凌月",
age : 18,
setName : function (name) {
name = this.name
},
setAge : function (age) {
age = this.age
}
}
console.log(ob.name,ob.age);
var ob2={
name:"凤千羽",
age:22,
setName : function (name) {
name = this.name
},
setAge : function (age) {
age = this.age
}
}
document.write(ob2.name,"\n"+ob2.age);
工厂模式
方式三: 工厂模式
套路: 通过工厂函数动态创建对象并返回
适用场景: 需要创建多个对象
问题: 对象没有一个具体的类型, 都是Object类型
// 工厂函数: 返回一个需要的数据的函数
function creatPerson(name, age) {
var ob = {
name: name,
age: age,
setName: function (name) {
name = this.name
},
setAge: function (age) {
age = this.age
}
}
return ob;
}
var p = creatPerson("凤千羽", 22);
var p2 = creatPerson("凌月", 18)
console.log(p);
console.log(p2);
自定义构造函数模式
方式四: 自定义构造函数模式
套路: 自定义构造函数, 通过new创建对象
适用场景: 需要创建多个类型确定的对象
问题: 每个对象都有相同的数据, 浪费内存
function Person(name, age) {
this.name = name
this.age = age
this.setName = function (name) {
name = this.name
}
this.setAge = function (age) {
age = this.age
}
}
var p = new Person("凤千羽", 22);
var p2 = new Person("凌月", 18)
console.log(p);
console.log(p2);
console.log(p instanceof Person)
构造函数+原型的组合模式
方式六: 构造函数+原型的组合模式
套路: 自定义构造函数, 属性在函数中初始化, 方法添加到原型上
适用场景: 需要创建多个类型确定的对象
function Person(name, age) {
this.name = name
this.age = age
//方法添加到原型中
Person.prototype.setName = function (name) {
name = this.name
}
Person.prototype.setAge = function (age) {
age = this.age
}
}
var p = new Person("凤千羽", 22);
var p2 = new Person("凌月", 18)
console.log(p);
console.log(p2);
console.log(p instanceof Person)