为什么下面的代码不会返回Person对象?它改为返回undefined fiddle
var factory = (function () {
function Person(name, salary) {
this.name = name;
this.salary = salary;
}
Person.prototype.talk = function () {
console.log('talking...');
}
return {
Person: Person
}
})();
var x = factory.Person('me', 100);
x.talk(); //cannot read property talk of undefined
答案 0 :(得分:3)
因为它不是一个合适的工厂:
var factory = (function () {
function Person(name, salary) {
this.name = name;
this.salary = salary;
}
Person.prototype.talk = function () {
console.log('talking...');
}
return {
Person: function(name,salary){
return new Person(name,salary);
}
}
})();
var x = factory.Person('me', 100);
x.talk(); //cannot read property talk of undefined
如果你不在Person上调用new,那么就没有原型继承。
编辑:你可以在工厂方法上更抽象,这样你就可以在不影响工厂的情况下改变构造函数的参数
return {
Person:function(){
return new (Function.prototype.bind.apply(Person,arguments));
}
}
或使构造函数成为impllcit工厂
function Person(name, salary) {
if(!(this instanceof Person)){
return new (Function.prototype.bind.apply(Person,arguments));
}
this.name = name;
this.salary = salary;
}
答案 1 :(得分:2)
var x = factory.Person('me', 100);
会调用factory.Person()
(仅设置this.name
和this.salary
并且不返回任何内容,因此undefined
)。
您想使用new
关键字:
var x = new factory.Person('me', 100);
// ^^^
答案 2 :(得分:2)
已经发布了相应的答案,但我只想通过确保构造函数始终返回Person
的新实例来显示实现相同结果的不同方法,即使new
是遗忘。
var factory = (function () {
function Person(name, salary) {
if (!(this instanceof Person)) return new Person(name, salary);
this.name = name;
this.salary = salary;
}
Person.prototype.talk = function () {
console.log('talking...');
}
return {
Person: Person
}
})();
var x = factory.Person('me', 100);
x.talk();