1. 对象字面量,相当于 var Obj = new Object();
这种方式的问题是如果需要多次创建对象,则需要重复代码多次,不利于代码的复用而且浪费内存
var Obj = {
name: 'a'
,method: function () {
alert(this.name);
}
}
Obj.method();
2. 工厂模式工厂方法创建对象的时候要为每个
对象创建各自私有的方法。同时由于为每个对象都创建逻辑相同的方法,浪费内存
var product = function (name) {
var obj = {
name: name
,method: function () {
alert(this.name);
}
}
return obj;
}
var res1 = product(1);
var res2 = product(2);
console.log(res1);
console.log(res2);
res1.method();
res2.method();
3. 构造函数与原型对象
构造函数模式用于定义私有属性,原型模式则用于定义共享的方法
var Base = function (name) {
this.name = name;
}
Base.prototype = {
method: function () {
alert(this.name);
}
}
var base1 = new Base(3);
var base2 = new Base(4)
base1.method();
base2.method();
console.log(base1);
console.log(base2);