Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript call prototype function from function inside constructor

I searched for this issue for quite a long time. Din't find any answer to satisfy my question. What I am trying is:

function myClass() {
    function privateFunction () {
        publicFunction();    //Error
    }
}

myClass.prototype.publicFunction = function() {
    this.variable = 1;
}
myClass.prototype.publicFunction2= function() {
    return this.variable;
}

This is giving me error. I am not getting what the real problem is:

What I tried:

this.publicFunction();

Then:

myClass.publicFunction();

Then:

myClass.prototype.publicFunction();

This works but it overrides for each object. Acts as if it is static across different JS objects.

like image 622
Veer Shrivastav Avatar asked Jul 04 '26 04:07

Veer Shrivastav


1 Answers

You haven't declared the prototype functions correctly. You are also missing the this keyword when calling the function publicFunction.

The private function (privateFunction) is not a member of the class, so if you want to call it as a function, you have to specify the context for it.

function myClass() {
    function privateFunction () {
        this.publicFunction();
    }

    privateFunction.call(this);
    document.write(this.publicFunction2()); // show value in Stackoverflow snippet
}

myClass.prototype.publicFunction = function() {
    this.variable = 1;
}

myClass.prototype.publicFunction2 = function() {
    return this.variable;
}

var myClassPrototype = new myClass();
like image 136
Guffa Avatar answered Jul 06 '26 17:07

Guffa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!