2

var Dog = function(name) { this.name = name; this.sayName(); }

Dog.prototype.sayName = function() {
  alert(this.name);
}

I'm creating new instance of Dog object Dog('Bowwow'), but method sayName() is undefined. Why?

Or maybe I should do something like (but I can't see difference)...

var Dog = function(name) {

  this.name = name;

  this.sayName();

  this.prototype.sayName = function() {
    alert(this.name);
  }
}

Thank you.

2
  • Your first code sample works great. What problem are you experiencing? You can see it working here: jsbin.com/uxevi3 Commented Apr 15, 2010 at 10:22
  • @Philippe Leybaert, see eBusiness answer. I've just forget to use new. Commented Apr 15, 2010 at 10:26

1 Answer 1

5

JavaScript is a little dodgy in this area, your code works as long as you call Dog using the new constructor.

new Dog("Hello world")

The new constructor makes this behave like you want it to. Otherwise it is totally different.

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

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.