Jonathan.Brink
Jonathan.Brink

Reputation: 25383

function prototype inheritance with new keyword

I was making sure that I understood JavaScript's new and prototype keywords correctly but some simple code I put together is not behaving as I expect.

var ClassA = function() {
    return {
        shout: function() {
             alert("I can shout");
        }
    };
};
ClassA.prototype.shoutLouder = function() {
     alert("I CAN SHOUT");
};

var instance = new ClassA();
instance.shout();

// why not available?
instance.shoutLouder();

When the instance variable attempts to invoke shoutLouder it's failing with "Uncaught TypeError: instance.shoutLouder is not a function".

But, in the mozilla docs, it says that when using new to create an object:

A new object is created, inheriting from Foo.prototype.

Where am I wrong in my understanding?

Here is a jsbin for the above code-snippit.

Upvotes: 0

Views: 34

Answers (2)

user5004821
user5004821

Reputation:

You're losing access to the function's (Class') prototype object because you're returning a new object out of the function:

var ClassA = function() {
    return {
        shout: function() {
             alert("I can shout");
        }
    };
};

whereas you should be doing:

var ClassA = function() {
    this.shout = function() {
        alert("I can shout");
    };
};

This will still give you access to the prototype object (and thus the delegation chain will still work) because the new keyword will return 'this' from the Class.

Upvotes: 3

guest271314
guest271314

Reputation: 1

ClassA returns a new , different object

 return {
        shout: function() {
             alert("I can shout");
        }
    };

Try

var ClassA = function() {
    this.shout = function() {
             alert("I can shout");            
    };
};
ClassA.prototype.shoutLouder = function() {
     alert("I CAN SHOUT");
};

var instance = new ClassA();

instance.shout();

// why not available?
instance.shoutLouder();

Upvotes: 1

Related Questions