1

I am trying to run a function of an object created using a constructor function. However, I am unable to do so as I keep getting and error saying “TypeError: mutant_cat.meow is not a function. (In 'mutant_cat.meow()', 'mutant_cat.meow' is undefined)”. This is my constructor function:

function Cat(legs, sound) {
    this.legs = legs;
    this.sound = sound;
    var meow = function() {
        document.write(sound);
    }
}

And this is where I create the object and attempt to run its function:

var mutant_cat = new Cat(5, "eeeeeee");
mutant_cat.meow();

Any help is greatly appreciated.

1
  • 1
    You need meow to be on this: this.meow = Better yet, put it on the prototype: Cat.prototype.meow = Commented Jun 28, 2019 at 17:30

2 Answers 2

2

This should fix it. You need to have the function be a property of the object by using "this".

function Cat(legs, sound) {
    this.legs = legs;
    this.sound = sound;
    this.meow = () => {
        document.write(this.sound);
    }
}

If you expect all your Cats to meow then you are better off using a prototype function as this is memory optimized and a shared function between all Cat instances rather than each Cat having its own duplicate meow function.

You can read more about prototype functions here: https://www.w3schools.com/js/js_object_prototypes.asp

Sign up to request clarification or add additional context in comments.

Comments

2

It's considered better practice to define your method on the prototype outside the constructor. This way we dont have to define the function for each instance of Cat:

function Cat(legs, sound) {
  this.legs = legs;
  this.sound = sound;
}

//Add the method to the protoype instead of constructor
Cat.prototype.meow = function() {
  console.log(this.sound);
}

var mutant_cat = new Cat(5, "eeeeeee");
mutant_cat.meow();

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.