1. 创建对象的几种方式
/** * 普通方式 */ var obj = {}; obj.name = ‘XingyaZhao‘; obj.age = 23; obj.intro = function () { return "My name is " + this.name + ", and I‘m " + this.age + "."; }; alert(obj.intro());
/** * 工厂模式 */ function createObject(name,age) { var obj = {}; obj.name = name; obj.age = age; obj.intro = function () { return "My name is " + this.name + ", and I‘m " + this.age + "."; }; return obj; } var obj1 = createObject(‘XingyaZhao‘,23); var obj2 = createObject(‘HailinWang‘,22); alert(obj1.intro()); alert(obj2.intro());
/** * 构造函数方式 */ function Person(name, age) { this.name = name; this.age = age; this.intro = function() { return "My name is " + this.name + ", and I‘m " + this.age + "."; }; } var zhao = new Person(‘XingyaZhao‘,23); var wang = new Person(‘HailinWang‘,22); alert(zhao.intro()); alert(wang.intro());
构造函数方式与工厂模式的区别
1.构造函数没有new Object,但它后台会自动var obj = new Object
2.this就相当于obj
3.构造函数不需要返回对象引用,它是后台自动返回的
构造函数方式的规范
1.构造函数也是函数,但函数名第一个字母大写
2.必须通过 new 构造函数名() 来创建对象,new Person()
原文:http://www.cnblogs.com/xingyazhao/p/7533258.html