javascript - 未定义不是函数

标签 javascript

我尝试使用未使用 IIFE 的私有(private)变量和原型(prototype)进行试验(这使得对象成为全局对象,因此没有唯一实例)。

我尝试了以下方法,但我对所看到的感到困惑。我可以在检查器中完美地看到它已定义,但它告诉我它实际上不是未定义的。

尽管在检查器中看到它已定义,但究竟是什么导致它未定义?

Screenshot

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

最佳答案

getNamePerson 函数的原型(prototype) 的属性。它不直接存在于Person 上,仅存在于Person实例 上(使用new 关键字创建)。

(注意 PersonFactory.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/

相关文章:

javascript - AngularJS:WAITING $scope 函数内的 ng-click 事件

javascript - 在 fadeOut 完成之前触发回调

javascript - 使用导航栏滚动 - 未捕获的类型错误 : Cannot read property 'top' of undefined

javascript - 动态调色板 - Jquery?

javascript - 为什么我的 .infobox 在放大或缩小时没有调整到父级?

javascript - 如何根据另一个请求的响应向 API 发出请求?无法在回调中调用 React Hook "useSwr"

javascript - 风 sails 多型号关联

javascript - 单击菜单栏时 JScript 隐藏 Logo

java - Vaadin:单击按钮后将文本字段中的文本设置为标签

javascript - 在将 Jquery 附加到 div 后,如何使用 Jquery 修改 css 元素?