getify / You-Dont-Know-JS

A book series on JavaScript. @YDKJS on twitter.
Other
179.37k stars 33.48k forks source link

This & Object Prototypes #646

Closed ygayl closed 8 years ago

ygayl commented 8 years ago

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!

getify commented 8 years ago

identity() should have been identify()

ygayl commented 8 years ago

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

getify commented 8 years ago

No worries. :)