0

In the code below, I change the Person.sayHello method to say 'Bye'. The debugger shows that the method has been changed, but the constructors method is still getting used. Why?

      function Person(){
          this.sayHello = function(){
              console.log("Hello");
          }
      }

      Person.sayHello = function(){
            console.log("Bye");
          }

      console.log(Person.sayHello);
      // function (){console.log("Bye");}

      var p = new Person();      
      p.sayHello();
      //Hello
Drenai
  • 9,332
  • 7
  • 43
  • 75
  • Wow, I didn't just ask a duplicate question, I even used the same Person object, and the same sayHello() method. That's f**king weird!! – Drenai Nov 28 '14 at 12:23

1 Answers1

1

Constructor methods are individual to each object instance. Thus, you cannot override them "globally" for all future instances again and can only change them on the instance itself:

 function Person() {
     this.sayHello = function () {
         console.log("Hello");
     }
 }

 var p = new Person();

 p.sayHello = function () {
     console.log("Bye");
 }

 p.sayHello();

Also, Person.sayHello should be Person.prototype.sayHello.

janfoeh
  • 10,235
  • 2
  • 30
  • 55