You-Dont-Know-JS icon indicating copy to clipboard operation
You-Dont-Know-JS copied to clipboard

This & Object Prototypes

Open ygayl opened this issue 10 years ago • 3 comments

Hi folks,

Trying to execute some example code from the book to try to in depth understand the "this and object prototypes" power in JavaScript but run through some troubles with the following code:

function Foo(who) {
    this.me = who;
}
Foo.prototype.identify = function() {
    return "I am " + this.me;
};

function Bar(who) {
    Foo.call( this, who );
}
Bar.prototype = Object.create( Foo.prototype );

Bar.prototype.speak = function() {
    console.log( "Hello, " + this.identity() + ".");
};

var b1 = new Bar( "b1" );
var b2 = new Bar( "b2" );

b1.speak();
b2.speak();

And I get the following error in the console (both in chrome and nodeJS)

TypeError: this.identity is not a function at Foo.Bar.speak (/Users/gayly/Desktop/coding/YDKJS/this_and_prototypes/protoypes_exercise/exo01.js:14:32) at Object. (/Users/gayly/Desktop/coding/YDKJS/this_and_prototypes/protoypes_exercise/exo01.js:21:4)

I thought that the statement javascript Bar.prototype = Object.create( Foo.prototype ); was responsible of prototype linked the two objects and by so as identify function is not on the Foo object, the "prototype inheritance" was going to go up in the chain and find the function not in Bar but in Foo object.

Please let me know what did I miss here.

Thanks!

ygayl avatar Jan 26 '16 03:01 ygayl

identity() should have been identify()

getify avatar Jan 26 '16 04:01 getify

Oh thanks very much! Sorry about that! ps: Thanks for the great job you did with those books!

ygayl avatar Jan 26 '16 04:01 ygayl

No worries. :)

getify avatar Jan 26 '16 04:01 getify