Question

I am trying to subclass native window object, but when I do so none of the window methods are callable in child class.

Here is an example below:

<script type="application/javascript" >


function baseWindow () {


}
baseWindow.prototype = window;

var mywindow  = new baseWindow();

window.alert('works'); // works of course
alert(window.document); // accessing property of course works

mywindow.alert('doesn\'t work'); // alert doesn't work in subclass error: TypeError: Illegal invocation
mywindow.__proto__.alert('works') // accessing it directly via __proto__ works
alert(mywindow.document); // accessing document property works 

</script>

Can someone explain why that doesn't work and if there is workaround ?

Thanks

Was it helpful?

Solution

As you figured out already, some properties of window are inherited properly, while others are not. Those that are not are methods that expect the object they are invoked on to be window which is obviously not the case in your example. By "expect" i mean they throw an error if the expectation is not met.

What you can do to avoid it is override those particular functions, perhaps by using the original functions somehow (depending on what you want to do with them).

function MyWindow(){
  this.alert = window.alert.bind(window); // override it to work!
}
MyWindow.prototype = window;

var mine = new MyWindow();
mine.alert(mine.location);

If you want many instances of Window and a single alert function shared between them and you don't want to alter window.alert, you need to add another object that inherits from window as prototype for Window:

function MyWindow() {
}
MyWindow.prototype = Object.create(window);

MyWindow.prototype.alert = window.alert.bind(window);

var mine = new MyWindow();
mine.alert(mine.location);

OTHER TIPS

I am trying to subclass native window object,

You cant.

Why? because window is not a function, and you cant call Window constructor.

Why? because the DOM is built that way.

function baseWindow () {


}
baseWindow.prototype = window

it's not even proper prototypal inheritance.

if Window constructor was callable one could write

function BaseWindow () {
  Window.call(this);
}
BaseWindow.prototype = Object.create(Window.prototype)

But you cant do that.

EDIT just to be clear,

window is an instance of Window, they are not the same.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top