Created
November 16, 2013 07:16
-
-
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)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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