We can 5 ways to create objects in JavaScript.
Lets understand how to Create it...
'use strict';
Example 1
Example 2
var fruit = {};
fruit.name = 'Mango';
fruit.color = 'Yellow';
console.log(`fruit name ${fruit.name} and color is ${fruit.color}`);
var fruit2 = { name: 'Mango', color: 'Yellow' };
console.log(`fruit name ${fruit2.name} and color is ${fruit2.color}`);
function Fruit(name, color) {
(this.name = name), (this.color = color);
}
var fruit3 = new Fruit('Mango', 'Yellow');
Example 4
var fruit4 = new Fruit('Donut', 'Sprinkled Yellow');
console.log(`fruit name ${fruit3.name} and color is ${fruit3.color}`);
console.log(`fruit name ${fruit4.name} and color is ${fruit4.color}`);
console.log(`Check fruit3 proto ${Fruit.prototype === fruit3.__proto__}`);
// console.log(`Property descriptor
// ${JSON.stringify(Object.getOwnPropertyDescriptor(fruit,'name'))}`)
var fruit5 = Object.create(Object.prototype, {
name: {
value: 'Mango',
enumerable: true,
writable: true,
configurable: true,
},
color: {
value: 'Yellow',
enumerable: true,
writable: true,
configurable: true,
},
});
console.log(`fruit name ${fruit5.name} and color is ${fruit5.color}`);
console.log(`Check fruit3 proto ${fruit.prototype === fruit5.__proto__}`);
var fruit6 = Object.create(Object.prototype, {
name: {
value: 'Mango',
enumerable: true,
writable: true,
configurable: true,
},
color: {
value: 'Yellow',
enumerable: true,
writable: false,
configurable: true,
},
});
fruit6.name = 'Sausages';
//compile error comment it later
//fruit6.color="Red";
for (var props in fruit6) {
console.log(`${props} : ${fruit6.color}`);
}
console.log(
`Fruit name ${fruit6.name} and color is ${
fruit6.color
} and proto ${JSON.stringify(fruit6.__proto__)}`
);
//Getter Setter
var fruit7 = {
color: 'Yellow',
get fruitcolor() {
return this.color;
},
set fruitcolor(val) {
this.color = val;
},
};
console.log(`Fruit default color is ${fruit7.fruitcolor}`);
fruit7.fruitcolor = 'Yellow';
console.log(`Fruit changed color is ${fruit7.fruitcolor}`);
console.log(`Check Fruit3 proto ${Fruit.prototype === fruit3.__proto__}`);
No comments:
Post a Comment