JavaScript(ES6) Object Literal Enhancement
Last Updated :
03 Jan, 2023
Object literal enhancement is used to group variables from the global scope and form them into javascript objects. It is the process of restructuring or putting back together.
Example 1:
<script>
var name = "Duke" ;
var color = "Brown" ;
var age = 5;
var dog = {name, color, age};
console.log(dog);
</script>
|
Output : The name, color and age are now keys of dog object.
{
name:"Duke",
color:"Brown",
age:5
}
Example 2: We can also create object methods with object literal enhancement.
<script>
var name = "Tike" ;
var color = "Black" ;
var age = 7;
var bark = function (){
console.log( "Woof Woof!!" );
}
var anotherDog = {name, color, age, bark};
anotherDog.bark();
</script>
|
Output:
Woof Woof!!
Example 3: We can also use “this” keyword to access the object keys.
<script>
var name = "Lilly" ;
var color = "White" ;
var age = 3;
var barkWithName = function (){
console.log( 'Woof Woof!!, I am '
+ this .name+ ' and I am a '
+ this .age+ ' years old, '
+ this .color+ ' coloured dog.Woof Woof!!' );
}
var yetAnotherDog = {name, color, age, barkWithName};
yetAnotherDog.barkWithName();
</script>
|
Output :
Woof Woof!!, I am lilly and I am a 3 years old,
white coloured dog.Woof Woof!!
Example 4: When defining object methods, it is no longer necessary to use the function keyword. Object literal enhancement allows us to pull global variables into objects and reduces typing by making the function keyword unnecessary.
<script>
var driver1 = {
name: "John" ,
speed: 50,
car: "Ferrari" ,
speedUp: function (speedup){
this .speed = this .speed + speedup;
console.log( "new speed = " + this .speed)
}
}
const driver2 = {
name: "Jane" ,
speed: 60,
car: "McLaren" ,
speedUp(speedup){
this .speed = this .speed + speedup;
console.log( "new speed = " + this .speed)
}
}
</script>
|
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...