Skip to content

Instantly share code, notes, and snippets.

@Madhuka
Created November 16, 2013 07:16
Show Gist options
  • Save Madhuka/7497044 to your computer and use it in GitHub Desktop.
Save Madhuka/7497044 to your computer and use it in GitHub Desktop.
There are four ways in which keys and values can be assigned to an object: (1,2 are ECMAScript 3 compatible approaches and 3,4 are ECMAScript 5 only compatible approaches)
//1 way
//setter
newObject.someKey = "some value";
//getter
var key = newObject.someKey;
//2nd way
// Set properties
newObject["someKey"] = "some value";
// Get properties
var key = newObject["someKey"];
//3rd way
Object.defineProperty( newObject, "someKey", {
value: "some value",
writable: true,
enumerable: true,
configurable: true
});
//simple way
var defineProp = function ( obj, key, value ){
config.value = value;
Object.defineProperty( obj, key, config );
};
// To use, we then create a new empty "car" object
var myCar= Object.create( null );
// Populate the object with properties
defineProp( myCar, "brand", "Toyota" );
defineProp( myCar, "year", "2009" );
defineProp( myCar, "bandnew", true );
//4th way
Object.defineProperties( newObject, {
"firstKey": {
value: "some vlaue",
writable: true
},
"secondrKey": {
value: "second value",
writable: false
}
});
//3 and 4 can be used any 1,2 getter mthod to get values
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment