1.工厂模式函数,解决多个相似对象的声明问题
function createObject(name, age) { //集中实例化的函数 var obj = new Object(); obj.name = name; obj.age = age; obj.run = function () { return this.name + this.age + '运行中...'; }; return obj; // return 对象 } var box1 = createObject('Lee', 100); //第一个实例 var box2 = createObject('Jack', 200); //第二个实例 alert(box1.run()); alert(box2.run()); //保持独立
//工厂模式解决了重复实例化的问题,但还有一个问题,那就是识别问题,因为根本无法搞清楚他们到底是哪个对象的实例。
alert(typeof box1); //Object
alert(box1 instanceof Object); //true
2.构造函数
function Box(name, age) { //构造函数模式 this.name = name; this.age = age; this.run = function () { return this.name + this.age + '运行中...'; }; } var box1 = new Box('Lee', 100); //new Box()即可 var box2 = new Box('Jack', 200); alert(box1.run()); alert(box1 instanceof Box); //很清晰的识别他从属于Box
3.原型
//构造函数: function Bbq(name,age){ this.name=name; this.age=age; this.run=function(){ return this.name+this.age+'退休'; } } var b1=new Bbq('abc',66); var b2=new Bbq('abc',66); alert(b1.run == b2.run); //false, //原型: function Box(){} //声明一个构造函数 Box.prototype.name = 'Lee'; //在原型里添加属性 Box.prototype.age = 100; Box.prototype.run = function () { //在原型里添加方法 return this.name + this.age + '运行中...'; }; //比较一下原型内的方法地址是否一致: var box1 = new Box(); var box2 = new Box(); alert(box1.run == box2.run); //true,方法的引用地址保持一致