我尝试使用未使用 IIFE 的私有(private)变量和原型(prototype)进行试验(这使得对象成为全局对象,因此没有唯一实例)。
我尝试了以下方法,但我对所看到的感到困惑。我可以在检查器中完美地看到它已定义,但它告诉我它实际上不是未定义的。
尽管在检查器中看到它已定义,但究竟是什么导致它未定义?
var Factory = Factory || {};
Factory.Person = function (aname)
{
var name = 'default';
function Person()
{
name = aname;
}
Person.prototype.getName = function() {
return name;
}
return Person;
};
var P = new Factory.Person('test');
alert(P.getName()); //Undefined
最佳答案
getName
是Person
函数的原型(prototype) 的属性。它不直接存在于Person
上,仅存在于Person
的实例 上(使用new
关键字创建)。
(注意 Person
和 Factory.Person
是非常不同的对象)。
由于您使用的是工厂模式:请勿触摸原型(prototype)或 new
关键字。
var Factory = Factory || {};
Factory.Person = function (aname)
{
// You need to check for aname here
var name = aname || 'default';
// There doesn't seem to be any point in making Person a function
var Person = {};
// No prototype here
Person.getName = function() {
return name;
}
return Person;
};
// No new keyword here
var P = Factory.Person('test');
alert(P.getName());
如果你想使用原型(prototype),那么你会这样做:
function Person(aname) {
this.name = aname || 'default';
};
Person.prototype.getName = function() {
return this.name;
}
var p = new Person('test');
alert(p.getName());
关于javascript - 未定义不是函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25289675/