Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript prototype function not overriding the original one

Learning javascript when I came across the concept of prototype. I succeeded in adding new methods to the cat class but failed in overriding the original talk method.

function cat(name) {
    this.name = name;
    this.talk = function() {
        alert( this.name + " : I'm a girl!" )
    }
}

cat.prototype.talk = function() {
    alert( this.name + " : I'm a dude!" )
}

cat1 = new cat("felix")
cat1.talk()

Why doesn't this alert the new text?

like image 847
datasn.io Avatar asked Apr 15 '09 13:04

datasn.io


1 Answers

‘function cat’ is just a function. Its prototype is an empty Object ({}). ‘new cat’ can be called to add members ‘name’ and ‘talk’ to a new Object. Beneath that new Object will be the function prototype, which is still {}.

var c= new cat('Tiddles');

c ownProperties: { 'name': 'Tiddles', 'talk': function() {...} }
c inherited: {}

Now when you write to ‘cat.prototype.talk’, you are adding members to that underlying object:

c ownProperties: { 'name': 'Tiddles', 'talk': function() {...} }
c inherited: { 'talk': function() {...} }

The ‘talk’ function set directly on the instance ‘c’ takes precedence over the ‘talk’ set indirectly on c's constructor prototype.

So you've mixed up two styles of inheritance here, the ‘this’-assigning method and the ‘prototype’ method.

Writing methods to prototypes has the advantage that you don't get redundant copies of the same members copied into every object instance; writing to instances has the advantage that it resolves the problem of bound methods. Which one you choose is up to you, but don't mix the two. If you want to go the prototype route, only ‘name’ should be written to ‘this’, because that's the only property that's specific to each instance.

like image 152
bobince Avatar answered Sep 20 '22 00:09

bobince