0

So the idea is to create a class Animal and the set properties to it as a new object

Here is what I have:

var name;
var type;
function Animal(name,type){
  this.type = type,
  this.name = name,
  toString = function(){return this.name + "is a " + this.type;}
};

var cat = new Animal('Max','cat');
cat.type;

everytime I run it - I seem to fail at the toString part? Pretty new and trying to learn this - is there something I am missing?

1
  • You don't need to declare those top variables, the arguments should be local to the function. Commented May 1, 2014 at 7:54

2 Answers 2

1

You don't need to declare those top variables, the arguments should be local to the function. The syntax is wrong too, you should use semicolons, not commas, and toString becomes a global variable since you forgot to use var.

What you want is this.toString so this works inside and refers to the instance, or better yet, create a method on the prototype so it's re-usable for all instances of Animal:

function Animal(name,type) {
  this.type = type;
  this.name = name;
}

Animal.prototype.toString = function() {
  return this.name + "is a " + this.type;
};
Sign up to request clarification or add additional context in comments.

Comments

0
function Animal(name, type) {
  this.type = type;
  this.name = name;
};

Animal.prototype.toString = function() {
  return this.name + "is a " + this.type;
}

var cat = new Animal('Max', 'cat');
console.log(cat); // Prints "Max is a cat"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.