0
var Foo = (function () {

    var cls = function () {
        this.prototype = {
            sayhi: function () {
                alert('hi');
            }
        };
    };

    cls.staticMethod = function () {};

    return cls;

})();

var f = new Foo();

Why can't i access my sayhi method? Doesn't this refer to the cls variable?

1 Answer 1

1

You are attempting to set the prototype property on every instance of cls. What you actually want to do is set the prototype property of cls itself:

var Foo = (function () {

    var cls = function () {}; // Constructor function

    cls.prototype = { // Prototype of constructor is inherited by instances
        sayhi: function () {
            alert('hi');
        }
    };

    return cls;

})();
Sign up to request clarification or add additional context in comments.

3 Comments

Good answer. Do you know what I'm missing here jsfiddle.net/6Wqsm/3? The output is cls {}, cls {sayhi: function}, but aren't both using the same prototype and should therefore share the sayhi function?
No, because the prototype is overwritten with a new object each time you call cls. Setting the prototype inside the constructor will cause all sorts of problems. For example, try window.f instanceof foo in your example - it will return false.
Oh, I didn't think about the overwrite part. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.