ES 2009

A method can be added to a class by declaring it inside the constructor function.

function MyClass1() { 
   this.MyMethod = function() {
      return "javascript";
   };
}
var myObject1 = new MyClass1();
console.log( myObject1.MyMethod() ); // "javascipt"

An additional method can be added to an object AFTER it has been created.

function MyClass2() { 
}
var myObject2 = new MyClass2();
myObject2.MyMethod = function() {
   return "javascript";
};
console.log( myObject2.MyMethod() ); // "javascipt"

An additional method can be added to a class / object constructor AFTER it has been declared.

function MyClass3() { 
}
var myObject3 = new MyClass3();
MyClass3.prototype.MyMethod = function() {
   return "javascript";
};
console.log( myObject3.MyMethod() ); // "javascipt"

Object.defineProperty

The following line:

MyClass3.prototype.MyMethod = function() { return "javascript"; }; 

is equivalent to:

Object.defineProperty(MyClass3.prototype, "MyMethod", { 
   value: function() {
      return "javascript";
   }
});

© 2022 Better Solutions Limited. All Rights Reserved. © 2022 Better Solutions Limited TopPrevNext