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
  • 11,315
  • 9
  • 48
  • 82

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,243
  • 2
  • 31
  • 56