I have the code below, where I cannot access a method (to list its name) unless I call the function itself. The method name isn't enumerated in the keys of the object, so how could I else display that method of the object?
class Car {
constructor(carname, caryear) {
this.name = carname;
this.year = caryear;
}
age() {
let date = new Date();
return date.getFullYear() - this.year;
}
}
let myCar = new Car("Ford", 2017);
document.getElementById("demo").innerHTML =
"My car is " + myCar.age() + " years old."; // 'My car is 4 years old.' --- now in 2021
alert(myCar.age); // it displays the function content
for (key in myCar) { // it only shows `name` and `year` but not the `age`
alert(key);
}
alert(Object.keys(myCar)); // it shows the aray name, year
<p id="demo"></p>
Is there any way to see age as a key inside the object myCar ? -- except the trivial one of putting some
this.age = function() {}
inside the constructor.
When invoking the method as myCar.age() it works (while it can't be seen as an own object key or method, so the age key is invisible for accessing it through the usual for loop from above, or through Object.keys(), Object.values() and Object.entries() as well.
I am not sure if this can be also related to the fact that Object.keys() creates an array only from user-defined objects (not from JS built-in ones) -- for example doing Object.keys(Math) will just return an empty array instead of that big list seen when doing console.dir(Math):
console.log(Object.keys(Math)); // []
The use case is when my code consumes some script from an external resource (the first script content above) where I cannot change the class definition (therefore using this.age = something()
probably won't be a choice) so I would need to check the methods and validate what is ok to run over my own created objects, etc.
More, I can't just use something as
if('age' in myCar){
alert("yes, i have that method");
}
as suggested by an answer here because I don't know beforehand the name of age
method (or the name of some other methods dynamically served from that script during the time).