I have created an object by defining the 'new' keyword from the object literal. But the problem is I can't access that object without looping. so is there any way to access that object?
const animal = {
animalDetails: function(a, b) {
this.a = a
this.b = b
},
animalOutPut: function() {
console.log(this.a, this.b)
},
}
// passing output by parameter ................................................................
animal.animalDetails('ape', 'Baboon')
// Call the object animal ................................................................
animal.animalOutPut()
// Create New Object Fruits from animal object literal ................................................................
let fruits = new animal.animalDetails('Apple', 'Blackberries')
for (let v in fruits) {
console.log(fruits[v])
}
CodePudding user response:
You want a class
class animal {
constructor(a, b){
this.a = a;
this.b = b;
}
animalOutput(){
console.log(this.a, this.b);
}
}
You can easily define the class let tiger = new animal("tiger", "grrr")
A class allows you to create multiple of them as well, much more useful then an object.
Hope this helped!
CodePudding user response:
You don't need to loop it. You can access the a
and b
properties just like you can with animal
.
You can't use fruits.animalOutput()
because animalOutput
is a property only of the animal
object. This object is not a prototype of objects created using new animalDetails()
, so there's no inheritance.
const animal = {
animalDetails: function(a, b) {
this.a = a
this.b = b
},
animalOutPut: function() {
console.log(this.a, this.b)
},
}
// passing output by parameter ................................................................
animal.animalDetails('ape', 'Baboon')
// Call the object animal ................................................................
animal.animalOutPut()
// Create New Object Fruits from animal object literal ................................................................
let fruits = new animal.animalDetails('Apple', 'Blackberries')
console.log(fruits.a, fruits.b);