Boy
Boy

Reputation: 612

how to properly call functions in prototype in js

How do I properly call the functions inside pretest?

I get this error: Uncaught TypeError: b.testmenow is not a function

    var pretest = function () {
        var MAX_NUM = 250.0;
    
        var prebase = function (NEW_NUM) {
            this.NEW_NUM = NEW_NUM ? NEW_NUM : true;
        };
    
        prebase.prototype.testmenow = function () {
            return this.NEW_NUM;
        };
        
        return prebase;
    };
    
    var b = new pretest(111);
    console.log(b.testmenow());

Upvotes: 0

Views: 38

Answers (1)

Chris
Chris

Reputation: 2806

You need to accept your input into new pretest(111) by adding n. And then you must instantiate your prebase constructor using n.

    var pretest = function (n) {
        var MAX_NUM = 250.0;
    
        var prebase = function (NEW_NUM) {
            this.NEW_NUM = NEW_NUM ? NEW_NUM : true;
        };
    
        prebase.prototype.testmenow = function () {
            return this.NEW_NUM;
        };
        
        return new prebase(n);
    };
    
    var b = pretest(111);
    console.log(b.testmenow());

It is strange that you have two constructors here, you can surely do this with one.

As Felix has deftly mentioned, you can call pretest(111) instead of new pretest(111).

Upvotes: 1

Related Questions