Reputation: 227
I made a typo in my code but it somehow still works.
let stuffs = [];
function stuff(thing) {
stuff[0] = thing; // should be stuffs[0] = thing;
}
stuff("item");
I expected to get an error but somehow it still works.
You can even get "item"
with stuff[0]
. What is going on here? Should I use this?
Upvotes: 0
Views: 78
Reputation: 11809
In JavaScript almost everything that has a structure inherits from Object.
In JavaScript objects can have any property.
With this statements you can see that a function
is an object actually, so you can set all the properties that you want to it, just like a simple {}
(with small limitations, as functions have another set of properties that plain objects don't have).
With this snippet you can check that functions inherit from Object
.
function myFunc() {
// empty! :-)
}
console.log("Func inherits from Object:", myFunc instanceof Object);
console.log("Array inherits from Object:", [] instanceof Object);
console.log("Object inherits from Object:", {} instanceof Object);
console.log("constant string inherits from Object:", "test" instanceof Object);
console.log(" * constant string DON'T inherits from Object but...");
console.log("String constructor inherits from Object:", String instanceof Object);
Upvotes: 3