0

Why does this work....

function Person(name) {
   this.name = name;
  }


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


var person = new Person("fred");

person.speak();

But not this..

function Person(name) {
   this.name = name;
        speak =  function() {
   alert(this.name);
}


var person = new Person("fred");

person.speak();

I am not understanding how inheritance works, or the javascript "prototype-chain".

Thanks.

3
  • read this. phrogz.net/js/classes/OOPinJS2.html Commented Jun 18, 2012 at 16:47
  • 3
    If you indent the code properly, it should be easier to spot the mistake Commented Jun 18, 2012 at 16:48
  • 3
    'I am not understanding how inheritance works, or the javascript "prototype-chain".' That's a very good position you're in. You just have to start some reading. This question has been answered countless times on this site alone. Commented Jun 18, 2012 at 16:48

2 Answers 2

4
function Person(name) {
   this.name = name;
        speak =  function() {
   alert(this.name);
}

should be

function Person(name) {
   this.name = name;
   this.speak = function () {
      alert(this.name);
   };
}
Sign up to request clarification or add additional context in comments.

1 Comment

Ahh, OP was creating a global speak function instead of attaching it to this
0

Actually it's variable scope that you're not understanding.

function Person(name) {
  this.name = name;

  speak = function() {
    alert(this.name);
  }
}

By omitting var before speak = ... here you've created a global variable named speak, not a variable within Person's scope. In a browser global variables are attached to the global object, window, so your code is equivalent to:

function Person( name ) {
  this.name = name;

  window.speak = function() { alert( this.name ); }

}

Douglas Crockford has written some related material about variable scope in prototypal inheritance that you should find enlightening.

3 Comments

That's not really equivalent, the function will be assigned to window.speak every time Person is invoked. And it will be different function object every time as well.
Perhaps I should have said "roughly equivalent." It was meant to be illustrative. Nevertheless I have changed the code.
@Jordan you're right about him creating a global but the problem here is failing to assign speak() to this. Using var would make it a private method of Person and so he would not be able to access it like he wants to with person.speak();.

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.