得到"未定义不是函数“;使用显示原型图案时出错

Getting "Undefined is not a function" error when using the Revealing Prototype Pattern

本文关键字:原型 显示 型图 出错 quot 未定义 函数 得到      更新时间:2023-09-26

我试图在JavaScript文件中使用Revearing Prototype Pattern来封装两个相关函数的集合。但是当页面加载时,它在调用.init函数时返回以下错误:

"未捕获类型错误:未定义不是函数。"

这是我的标记模式。

<script>
    $(function () {
        testProto1.init();
        testProto2.init();
    });
</script>

这是我的JavaScript文件中的模式。

var testProto1 = function () {
};
testProto1.prototype = function () {
    var init = function () {
        alert("init 1");
    };
    return {
        init: init
    }
}();

var testProto2 = function () {
};
testProto2.prototype = function () {
    var init = function () {
        alert("init 2");
    };
    return {
        init: init
    }
}();

这可能是我的一些基本语法错误,如果是重复的,我深表歉意。为什么我看到这个错误,我该如何修复它?谢谢

看起来您正在使用原型的概念&函数实例在很多方面都不正确。

如果您希望能够访问原型,则需要使用new运算符instantiate一个函数。

从你试图实现的目标来看:

var testProto1 = function () { };
// Create your methods in object notation within your prototype
testProto1.prototype.init = function () { 
    alert('init called');
};

现在,如果你想调用这个,你必须instantiate它!

var proto1 = new testProto1();
// NOW you can call .init! Because the prototype was actually created
proto1.init(); // alerts 'init called!'

您可以从该对象的实例访问原型的属性,因此这将起作用:

var a=new testProto1();
a.init();

如果你想从testProto1访问init函数,你必须写:

testProto1.prototype.init();

所以你的代码看起来像:

    $(function () {
    testProto1.prototype.init();
    testProto2.prototype.init();
});