简体   繁体   中英

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

I'm trying to employ the Revealing Prototype Pattern in a JavaScript file to encapsulate two collections of related functions. But when the page loads, it returns the following error at the call to the .init function:

"Uncaught TypeError: Undefined is not a function."

Here is the pattern for my markup.

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

And here is the pattern in my JavaScript file.

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
    }
}();

This is probably some basic syntax error on my part, and I do apologize if it's a duplicate. Why am I seeing this error and how do I fix it? Thanks.

It looks like you're using the concepts of prototypes & function instances incorrectly in a lot of ways.

You need to instantiate a function with the new operator if you want to be able to access prototypes.

From what it looks like you're trying to achieve this:

var testProto1 = function () { };

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

Now if you want to call this, you have to instantiate it!

var proto1 = new testProto1();

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

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

you can access prototype's properties from instances of this Object, so this will work:

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

if you want to acces init function from testProto1 you must write:

testProto1.prototype.init();

so your code will look like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM