Reputation: 11
var cat = {
name: "Gus",
color: "gray",
age: 15,
printInfo: function() {
console.log("Name:", this.name, "Color:", this.color, "Age:", this.age);
nestedFunction = function() {
console.log("Name:", this.name, "Color:", this.color, "Age:", this.age)
}
nestedFunction();
}
}
cat.printInfo()
//PRINTS : Name: Gus Color: gray Age: 15 -- Printed by printInfo
//PRINTS : Name: undefined Color: undefined Age: undefined -- Printed by nestedFunction
class info {
constructor(name,color,age){
this.name = name
this.color = color
this.age = age
}
printInfo = function(){
console.log("Name:", this.name, "Color:", this.color, "Age:", this.age);
nestedFunction=function(){
console.log("Name:", this.name, "Color:", this.color, "Age:", this.age);
}
nestedFunction();
}
}
var obj=new info("thomas","orange","26")
obj.printInfo()
//PRINTS : Name: thomas Color: orange Age: 26 (Printed by printInfo)
ReferenceError: nestedFunction is not defined (It throws error after that) In the first case direct object is made and in the case 2 object is made using class.
But the output is different In the class object it throws error as nestedFunction is not defined
Please tell me the difference between direct object and object made using class template.
Upvotes: 1
Views: 49
Reputation: 5767
In both cases you forgot the var before the declaration of nestedFunction and when you give this as an argument to that function, then in both cases your code works:
var nestedFunction = function(cat) {
console.log("Name:", cat.name, "Color:", cat.color, "Age:", cat.age)
}
nestedFunction(this);
By the way: in the second case it is much cleaner to avoid the usage of a class, the new keyword and their side effects, and to use instead your object from the first case with behavior delegation:
var cat = {
setData(name, color, age) {
this.name = name;
this.color = color;
this.age = age;
},
printInfo: function() {
console.log("Name:", this.name, "Color:", this.color, "Age:", this.age);
var nestedFunction = function(cat) {
console.log("Name:", cat.name, "Color:", cat.color, "Age:", cat.age)
}
nestedFunction(this);
}
}
var gus = Object.create(cat); //behavior delegation
var thomas = Object.create(cat); //behavior delegation
gus.setData("Gus", "gray", 15);
thomas.setData("thomas", "orange", 26);
gus.printInfo(); //Name: Gus Color: gray Age: 15
//Name: Gus Color: gray Age: 15
thomas.printInfo(); //Name: thomas Color: orange Age: 26
//Name: thomas Color: orange Age: 26
Upvotes: 1