1

Why my person doesn't say "Hello" when calling one self method ? How to fix this?

var Person = (function () {

  function Person() {
    this.prototype.say();
  }

  Person.prototype.say = function() {
    alert("hello");
  }

  return Person;
})();

var person = new Person();
4
  • Don't use the same name for the inner and outer Person variables. Commented Feb 23, 2016 at 19:22
  • @Barmar Why? This is a pretty common practice. Commented Feb 23, 2016 at 19:24
  • because you're getting confused about which Person's prototype you're assigning to. You want to assign to the outer Person.prototype, but instead you're assigning to the inner one. Commented Feb 23, 2016 at 19:28
  • @Barmar return Person; They're the same thing. It's assigned to the prototype of the "inner" Person which is then returned and assigned to the "outer" Person. They're using an IIFE. Commented Feb 23, 2016 at 19:31

2 Answers 2

4

To call function on the current object you shouldn't use prototype, just call it(this.say()).

var Person = (function() {
    function Person() {
        this.say();
    }

    Person.prototype.say = function() {
      alert("hello");
    }
    return Person;
})();

var person = new Person();

To learn more about OOP in javascript you can read docs on MDN

Nice doc and examples on MDN for inheritance and prototype chain

Good notice from @FelixKling

The object this refers to doesn't have a prototype property. Only functions have a prototype property.

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

5 Comments

I tried on fiddler does not seem to work jsfiddle.net/dtxfj1rp
@user310291 I've update code
Thanks, now it works. Can you explain further why yours work and not mine ? I'm relearning javascript OOP.
@user310291: The object this refers to doesn't have a prototype property. Only functions have a prototype property. The value of that property becomes the prototype of the value of this. If you want to learn how prototypes work, I recommend reading github.com/getify/You-Dont-Know-JS/blob/master/… .
@FelixKling good link, am reading it.
1

isvforall's solution is fine.

The key point is that the 'prototype' defines the functions available on the object you are 'constructing' in the Person() constructor - referred to as 'this.'

The prototype is the shared base definitions for all of the objects constructed with Person(). Inside the Person() constructor and the other prototype methods, the instance itself is referenced with 'this'.

See documents such as https://developer.mozilla.org/en-US/docs/Web/JavaScript/Inheritance_and_the_prototype_chain for Reference.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.