Imagine having this:
var exampleObject = {age: 25, name: 'John'};
If you do this:
Object.keys(exampleObject); // it will return ['age', 'name']
Now, what if you want to add this functionality to the object prototype? You can achieve it like so:
Object.prototype.getKeys = function(){
return Object.keys(this);
};
exampleObject.getKeys(); // returns ['age', 'name']
Next objective: Let's take all functions associated with the Object and incorporate them into the prototype. Here's how I approached it:
Object.getOwnPropertyNames(Object)
.filter(function(element){
return Object[element] && Object[element].constructor.name === "Function";
})
.forEach(function(functionName){
Object.prototype[functionName] = function(){
return Object[functionName].apply(this, Array.prototype.slice.call(arguments, 1));
};
});
Essentially, we are retrieving all functions linked to the Object, then looping through to attach them to the prototype.
However, when trying exampleObject.getKeys()
, an error pops up stating
TypeError: Object.keys called on non-object
.
Can anyone spot the mistake here?