blog
blog copied to clipboard
Javascript创建对象的几种模式
一、原始模式
原始模式主要是两种,对象字面量和Object构造。如下
var a = {
name : 'share',
age : 19,
method : function(){console.log(this.name)}
}
var a = new Object();
a.name = 'share';
a.age = 19;
a.method = function(){console.log(this.name)}
原始模式有一个问题,如果要批量生成多个a1、a2,就得不断重复copy代码了,所以有了下面的方法,工厂模式、构造器模式、圣杯模式等。
二、工厂模式
function parent(name){
var child = {};
child.name = name;
child.method = function(){
console.log(this.name);
};
return child;
}
var childA = parent('lily');
var childB = parent('lucy');
childA.method(); //lily
childB.method(); //lucy
console.log(childA.method === childB.method) //false
工厂模式就是批量化生产,简单调用就可以进入造人模式。 由于是工厂暗箱操作的,所以你不能识别这个对象到底是什么类型。 经典工厂模式是直接执行parent()方法,而不是通过new的方式。混合工厂模式尽量不用。 工厂模式中每生成一个子类,就会重复生成相应的方法,代码臃肿。
三、构造函数模式
function Parent(name){
this.name = name;
this.method = function(){
console.log(this.name);
}
}
var childA = new Parent('lily');
var childB = new Parent('lucy');
childA.method(); //lily
childB.method(); //lucy
console.log(childA.method === childB.method) //false
构造器模式,用new的方式构造子类。同时构造器函数首字母大写。 如果直接执行Parent(),那么属性方法都赋值给window对象了。
四、原型模式
function Parent(){}
Parent.prototype.name = 'share';
Parent.prototype.method = function(){console.log(this.name)};
var childA = new Parent();
var childB = new Parent();
console.log(childA.name === childB.name); //true
console.log(childA.method === childB.method); //true
或者
function Parent(){}
Parent.prototype = {
name : 'share',
method : function(){console.log(this.name)}
};
var childA = new Parent();
var childB = new Parent();
console.log(childA.name === childB.name); //true
console.log(childA.method === childB.method); //true
原型属性和方法的共享,即所有实例中都只是引用原型中的属性方法,任何一个地方产生的改动会引起其他实例的变化。
五、构造器和原型的混合模式
function Parent(name){
this.name = name;
}
Parent.prototype = {
method : function(){
console.log(this.name);
}
}
var childA = new Parent('lily');
var childB = new Parent('lucy');
console.log(childA.name === childB.name); //false
console.log(childA.method === childB.method); //true
将构造器和原型模式的优点结合起来了。 需要独立的属性方法放入构造函数中,而可以共享的部分则放入原型中,这样做可以最大限度节省内存而又保留对象实例的独立性。
六、Object.create()方法
Object.create()可以接收两个参数:提供原型的对象,可选属性对象(这个对象包含对新创建对象的配置)。
var Car = {
drive: function (miles) {
return this.odometer += miles;
}
};
var tesla = Object.create(Car, {
'odometer': {
value: 0,
enumerable: true
}
));
console.log(tesla.drive(10));//10