js通过代码来理解构造函数的实现过程
原生实现
function Person(name){
this.name = name;
};
Person.prototype.getName = function(){
return this.name;
}
var a = new Person('sven');
console.log(a.name);
console.log(a.getName());
console.log(Object.getPrototypeOf(a) === Person.prototype);
代码实现
function Person(name){
this.name = name;
};
Person.prototype.getName = function(){
return this.name;
}
var objectFactory = function(){
var obj = new Object(),
Constructor = [].shift.call(arguments);
obj.__proto__ = Constructor.prototype;
var ret = Constructor.apply(obj, arguments);
return typeof ret === "object" ? ret: obj;
}
var a = objectFactory(Person, "sven");
console.log(a.name);
console.log(a.getName());
console.log(Object.getPrototypeOf(a) === Person.prototype);
下面的代码可以实现原生的效果,参考自JavaScript设计模式与开发实践,[p18-p20]