TestDummyPro
TestDummyPro

Reputation: 31

Creating a Class and calling on it's properties (javascript)

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?

Upvotes: 0

Views: 34

Answers (2)

elclanrs
elclanrs

Reputation: 94101

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;
};

Upvotes: 1

blabus
blabus

Reputation: 845

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"

Upvotes: 0

Related Questions