I’ve been trying to write a custom JavaScript console for use at school where they block inspect, and I’ve gotten quite far, but my stringify method throws an error when I try to crawl an HTMLAnchorElement. I’ve narrowed it down to an Illegal invocation
for trying to access properties of the prototype of document.createElement("a")
.
const x = document.createElement("a");
const y = Object.getPrototypeOf(x);
console.log(y["href"]);
This code throws the Illegal invocation
. However, this
const y = HTMLAnchorElement;
console.log(y["href"]);
doesn’t. I’ve looked into the Object.getOwnPropertyDescriptor(Object.getPrototypeOf(document.createElement("a")), "href").get()
and that seems to be the problem. Is there a fix (perhaps binding the this
value)?
2
Answers
In the second example it does not throw an exception because
HTMLAnchorElement
is a constructor, (thus a function), and functions don’t have a propery"href"
thus this is undefined. On the first and third example you get an Illegal invocation error because as explained here the context is lost. You can look the link for more detail, but in short, as you probably suspected the function internally uses this, so when its called outside of the context, it throws an error.Yes, you can fix it binding the right context to it
For example in your third example
Object.getOwnPropertyDescriptor(Object.getPrototypeOf(document.createElement("a")), "href").get()
the get seems to expect the element that was created as context, thus this works:but its not always clear what is the expected context, so I don’t know what you are trying to acomplish but maybe its not the best way.
Because you’re looking for
HTMLAnchorElement.prototype
.HTMLAnchorElement["href"]
just doesn’t exist.Yes, which is done by accessing the
href
property via the element itself, i.e.x["href"]
.