Below code demonstrates creation of objects using two techniques:
// object creation - Technique 1 - using JSON
var person1 = {
name: "MS Dhoni",
"firstName": "Mahendra",
city: "Ranchi",
team: "Chennai Super Kings",
details: {
hobbies: ["cooking","cricket","chess"],
location: "India"
},
greeting: function() {
console.log("welcome "+this.name);
}
}
// object creation - Technique 2 - using new Object()
var person2 = new Object();
person2.name = "V Kohli";
person2.firstName = "Virat";
person2.city = "Delhi";
person2.team = "Royal Challengers Bangalore";
person2.details = {
hobbies: ["sleeping","cricket","listening songs"],
location: "India"
};
person2.greeting = function() {
console.log("welcome "+this.name);
}
// Printing the person name to console
console.log(person1);
console.log(person2);
person1.greeting();
person2.greeting();
Refer:
Practice at:
http://jsbin.com
// object creation - Technique 1 - using JSON
var person1 = {
name: "MS Dhoni",
"firstName": "Mahendra",
city: "Ranchi",
team: "Chennai Super Kings",
details: {
hobbies: ["cooking","cricket","chess"],
location: "India"
},
greeting: function() {
console.log("welcome "+this.name);
}
}
// object creation - Technique 2 - using new Object()
var person2 = new Object();
person2.name = "V Kohli";
person2.firstName = "Virat";
person2.city = "Delhi";
person2.team = "Royal Challengers Bangalore";
person2.details = {
hobbies: ["sleeping","cricket","listening songs"],
location: "India"
};
person2.greeting = function() {
console.log("welcome "+this.name);
}
// Printing the person name to console
console.log(person1);
console.log(person2);
person1.greeting();
person2.greeting();
Refer:
- https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Objects/Basics
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Working_with_Objects
Practice at:
http://jsbin.com
No comments:
Post a Comment