I'm trying to extend the built-in "URL" object and add a custom getter:
class Foo extends URL {
constructor(s) {
super(s);
}
get a() { return 1; }
set a(x) { return; }
}
let f = new Foo("http://abc.com"); console.log(f.a);
console.log(f instanceof URL);
console.log(f instanceof Foo);
The output is:
undefined
true
false <----- why!?
The code works fine if pasted into the console window (it prints 1, true, true meaning it successfully extended the URL object).
It also works fine to extend other objects. For example,
class Foo extends Date {
constructor(s) {
super(s);
}
get a() { return 1; }
set a(x) { return; }
}
let f = new Foo("http://abc.com"); console.log(f.a);
console.log(f instanceof Date);
console.log(f instanceof Foo);
prints
What is going on? Why can I extend Date but not URL? Why does it work in a console but not in a user.js script? I'm particularly puzzled that using the new keyword on the Foo class creates an object for which instanceof Foo returns false.
Note that a gross work-around is to not extend URL at all but to just have Foo's constructor create an instance property which is a URL. This works:
class Foo {
constructor(s) {
this.url = new URL(s);
}
get a() { return 1; }
set a(x) { return; }
}
let f = new Foo("http://abc.com");
console.log(f.url.hostname);
console.log(f.a);