簡體   English   中英

使用顯示原型模式時出現“未定義不是函數”錯誤

[英]Getting “Undefined is not a function” error when using the Revealing Prototype Pattern

我正在嘗試在JavaScript文件中使用顯示原型模式來封裝兩個相關功能的集合。 但是,當頁面加載時,它會在調用.init函數時返回以下錯誤:

“未捕獲的TypeError:未定義不是函數。”

這是我的標記模式。

<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則必須instantiate它!

var proto1 = new testProto1();

// NOW you can call .init! Because the prototype was actually created

proto1.init(); // alerts 'init called!'

您可以從此Object的實例訪問原型的屬性,因此可以使用:

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

如果要從testProto1訪問init函數,則必須編寫:

testProto1.prototype.init();

因此您的代碼將如下所示:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM