Lykos Hughie
Lykos Hughie

Reputation: 1

JavaScript: how to call a function on the prototype property, from inside another function on the prototype property, all inside a closure?

I am hoping that someone can help me figure out how to do this correctly, rather than just "make it work."

I am trying to use an object inside a closure, and having scope issues:

var Why = function() {
    this.foo = 'bar';
}
Why.prototype.explain = function () {
    alert(this.foo);
}
Why.prototype.doIt = function () {
    this.explain();
}

(function() {

    document.addEventListener("DOMContentLoaded", function(event) {
        var why = new Why();
        why.doIt();
    });

})();

And I get in console:

Uncaught TypeError: this.explain is not a function

I could use

Why.prototype.explain.call();

but that just seems wrong, and when I actually do that... this.foo is undefined anyway, so it's obviously not the right approach.

If I remove the self calling function as follows...

var Why = function() {
    this.foo = 'bar';
}
Why.prototype.explain = function () {
    console.log(this.foo);
}
Why.prototype.doIt = function () {
    // Why.prototype.explain.call();
    this.explain();
}

// (function() {

    document.addEventListener("DOMContentLoaded", function(event) {
        var why = new Why();
        why.doIt();
    });

// })();

then it works of course, but:

what am I missing and where/how can I learn it?

Thanks in advance.

Upvotes: 0

Views: 45

Answers (1)

SLaks
SLaks

Reputation: 887509

Your code is parsed as

Why.prototype.doIt = function () { ... }(function() { ... });

You're calling the function you want to assign to the prototype, then assigning its return value. Since it returns undefined, Why.prototype.doIt doesn't exist.

You need a semicolon.

Upvotes: 2

Related Questions