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?
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?
Share Improve this question asked Apr 15, 2009 at 13:31 datasn.iodatasn.io 12.9k28 gold badges122 silver badges157 bronze badges2 Answers
Reset to default 16‘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.
the function attached in the beginning is attached to the object (1 function for each instance). the other one is attached to the prototype (1 function shared by all instances).
members at the object level override those at the prototype level.