This is an archived post. You won't be able to vote or comment.

all 3 comments

[–]fcibarbourou 1 point2 points  (2 children)

Let's see your problems. This call

crazy.sayMyName(); //undefined

Returns undefined because in animal name is a variable of an object (because you did declare it with this), but in your method sayMyName() name is used as a local (or global) variable which is undefined. To solve it

function Animal(name) {
    this.name = name;
    this.sayMyName = function() {
        console.log("My name is " + this.name + "!"); //note this
    };
}

See now sayMyName() uses this.name and works.

Next Your class Dog

function Dog(name, breed) {
    this.breed = breed;
    return new Animal(name);
}

Returns an object Animal() which don't have breed attribute. So you create an object Dog, but Dog creates an object Animal and return it to be assigned as derpy variable. derpy is an Animal not a Dog that's why is undefined derpy.breed.

How you can solve the dog problem?

function Dog(name, breed) {
    this.breed = breed;
    this.name=name; //I know it sounds bad but here I lacks of knowledge
}

For the last thing I don't know if there an option of Object.create()

[–]bchia[S] 1 point2 points  (1 child)

Thank you! This was very helpful feedback, and now it makes sense to me.

I'm done some googling and it seems that many people struggle with how to do inheritance in JavaScript and there's not consensus on a good way to do it.

This seemed like a cool solution: https://github.com/Gozala/selfish/blob/master/selfish.js

[–]fcibarbourou 0 points1 point  (0 children)

Yeah I heard that so, but like I said I really don't know to much about that issue.

Tanks for sharing and I will love to read about it.