ES 2009

A property can be added to a class by declaring it inside the Constructor Function

function MyClass1 ( DefaultValue ) { 
   this.Property_Name = DefaultValue;
}
var myObject1 = new MyClass1("javascript");
console.log( myObject1.Property_Name ); // "javascript"

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

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

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

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

Object.defineProperty

The following line:

MyClass3.prototype.Property_Name = "javascript"; 

is equivalent to:

Object.defineProperty(MyClass3.prototype, "Property_Name", { 
   value: "javascript",
   writable: true
});

which is also equivalent to:

var _propname = "javascript"; 
Object.defineProperty(MyClass3.prototype, "Property_Name", {
   get: function() { return _propname; }
   set: function(value) { _propname = value; }
});

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