0

I've been doing a lot of HTML and CSS and now I'm doing a JS tutorial. I ran into this problem though. I don't know how to access the prototype.

Instructions:

Create a class named Animal with two properties, name and numLegs. The Animal constructor should have two arguments whose values are assigned to name and numLegs.

Next, change the prototype of Animal and add a method sayName that prints to the console "Hi my name is [name]", where [name] is the value of name.

Click "Stuck? Get a hint!" for examples of how to create a class and how to add a method to an object's prototype.

Finally, we have provided the last two lines to test your constructor and sayName method. Don't change these!

Here is my code:

// create your Animal class here
function Animal(name, numLegs)={
    this.name=name;
    this.numLegs=numLegs;

    this.sayName=function(){
        console.log("Hi, my name is "+this.name);
    }
}


// create the sayName method for Animal

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();

I get a syntax error. What gives?

Community
  • 1
  • 1
user3695903
  • 37
  • 1
  • 7
  • 1
    Side note, you didn't follow directions! `sayName` should be added to the prototype, not defined within the constructor. – Tserkov Dec 29 '14 at 05:09
  • Inheritance, constructor functions and prototype are covered in detail here: http://stackoverflow.com/a/16063711/1641941 – HMR Dec 29 '14 at 08:27
  • Unrelated tip: It might be smart to assign 'this' to a named variable inside the constructor to avoid inheritance issues with `this`. e.g. `var self = this;` at the beginning of the constructor, then use `self` in place of `this` inside of internally defined functions. That way it will always use the constructor scope's `this` instead of the current function's scope `this`. – Makaze Dec 29 '14 at 18:44

3 Answers3

5

I believe the syntax error is due to the equal sign after your function declaration:

function Animal(name, numLegs)=

If you remove the equal sign, the function doesn't throw a syntax error anymore (I tried it just now in Chrome's console).

wmock
  • 5,382
  • 4
  • 40
  • 62
0

You can check my code and it's working :

Animal.prototype.sayName = function(){
    console.log("Hi my name is" + " " + this.name);
};
Machavity
  • 30,841
  • 27
  • 92
  • 100
Alik
  • 5
  • 2
0
// create your Animal class here
function Animal(name, numLegs) {
    this.name = name;
    this.numLegs = numLegs;

    // create the sayName method for Animal
    Animal.prototype.sayName = function() {
        console.log("Hi my name is " + [this.name]);
    }
};

// provided code to test above constructor and method
var penguin = new Animal("Captain Cook", 2);
penguin.sayName();
Andre Hofmeister
  • 3,185
  • 11
  • 51
  • 74