var myHonda = {color: "red", wheels: 4, engine: {cylinders: 4, size: 2.2}}
就是new Object()
的语法糖,同样同样的。html
function createCar(){ var oTemp = new Object(); oTemp.name = arguments[0]; //直接给对象添加属性,每一个对象都有直接的属性 oTemp.age = arguments[1]; oTemp.showName = function () { alert(this.name); };//每一个对象都有一个 showName 方法版本 return oTemp; }; var myHonda = createCar('honda', 5)
只是给new Object()
包了层皮,方便量产,并无本质区别,姑且算做建立对象的一种方式。闭包
function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; this.getName = function() { return this.name; }; } var rand = new Person("Rand McKinnon", 33, "M");
上面构造函数的 getName 方法,每次实例化都会新建该函数对象,还造成了在当前状况下并无卵用的闭包,因此构造函数添加方法用下面方式处理,工厂模式给对象添加方法的时候也应该用下面的方式避免重复构造函数对象函数
function Person(name, age, sex) { this.name = name; this.age = age; this.sex = sex; this.getName = getName } function getName() { return this.name; };
构造函数建立对象的过程和工厂模式又是半斤八两,至关于隐藏了建立新对象和返回该对象这两步,构造函数内 this 指向新建对象,没什么不一样。
最大不一样点: 构造函数创造出来的对象 constructor 属性指向该构造函数,工厂模式指向 function Object(){...}
。
构造函数至关于给原型链上加了一环,构造函数有本身的 prototype,工厂模式就是个普通函数。说到这儿我上一句话出现了漏洞,工厂模式的 constructor 指向哪得看第一句话 new 的是什么。this
https://www.cnblogs.com/lihuanqing/p/7561480.htmlprototype