xxxxxxxxxx
var myDog = {
"name": "Happy Coder",
"legs": 4,
"tails": 1,
"friends": ["freeCodeCamp Campers"]
};
myDog.bark = "woof";
// or
myDog["bark"] = "woof";
xxxxxxxxxx
let yourObject = {};
//Examples:
//Example 1
let yourKeyVariable = "yourKey";
yourObject[yourKeyVariable] = "yourValue";
//Example 2
yourObject["yourKey"] = "yourValue";
//Example 3
yourObject.yourKey = "yourValue";
xxxxxxxxxx
//JavaScript example code to demonstrate the use of Object.defineProperty() method
let obj = {}; //empty JavaScript object obj
Object.defineProperty(obj, 'id', { //using Object.defineProperty() method of JavaScript object class
value: 101,
writable: false //configured writable property as false, and hence, the id property of object obj can't be changed now
});
obj.id = 412; //no effect on 'id' property
console.log("Object ID:",obj.id); //prints 101
Object.defineProperty(obj, 'name', { //using Object.defineProperty() method of JavaScript object class
value: 'Mayank',
writable: true //configured writable property as true, and hence, the name property of object obj can be changed now
});
obj.name = 'Mayank Jain'; //modifying the name property of object obj (writable property is set to true)
console.log("Object Name:",obj.name); //prints 'Mayank Jain'
Try it yourself
xxxxxxxxxx
// constructor function
function Person () {
this.name = 'John',
this.age = 23
}
// creating objects
let person1 = new Person();
let person2 = new Person();
// adding property to person1 object
person1.gender = 'male';
// adding method to person1 object
person1.greet = function () {
console.log('hello');
}
person1.greet(); // hello
// Error code
// person2 doesn't have greet() method
person2.greet();