Dynamically creating properties on objects using javascript
Object oriented JavaScript provides great flexibility when coding on the client side. Properties on the Javascript object help set values that can be used within the object to manage and use the data.
A background on what I mean by properties in javascript.
In javascript properties can be created by defining variables on a literal object.
For example
var obj = {
property1: '',
property2: ''
};
Now one can access these properties by using
obj.property1 = 'some value';
obj.property2 = 'some other value';
and similarly, they can also be used within functions that are within the object obj
.
For example:
var obj = {
property1: '',
property2: '',
foo : function(){
console.log(obj.property1);
}
};
So now that we know how to create properties on javascript objects, let us look at how to create dynamic properties on Javascript
There are 2 ways to do this
Defining a dynamic property like an Array on the Javascript Object
Let us take the same example as above:
var obj = {
property1: '',
property2: ''
};
To create a dynamic property on the object obj
we can do:
obj['property_name'] = 'some_value';
what this does is, it creates a new property on the object obj
which can be accessed as
console.log(obj.property_name);
This will output the value some_value
on the console.
- Defining a dynamic property using
Object.defineProperty
. The documentation for Object.defineProperty
Example:
// Example of an object property added with defineProperty with a data property descriptor
Object.defineProperty(obj, "property3", {value : 'some value',
writable : true,
enumerable : true,
configurable : true});
// 'property3' property exists on object obj and its value is 37