Partager via


Function pointer method calls

Earlier versions of Windows Internet Explorer supported caching a pointer to a method and then using the cached pointer to call the method. As of Windows Internet Explorer 9, This support was removed to improve interoperability with other browsers.

A common practice on webpages targeting older versions of Internet Explorer was to save common methods to a variable and use that variable as a proxy for the method in order to make JavaScript code more compact:

var d = document.writeln;
d("<script language=VBScript>");

As of Internet Explorer 9, an object is required in order to invoke the method. By default the window object is provided in global scope (such as in the previous example). However, the window object does not have a method writeln, so the JavaScript error message "Invalid calling object" is reported.

The JavaScript error message "Invalid calling object" is reported when using a cached pointer to call a method in Internet Explorer 9.

Use the call method (a property of all functions) to explicitly provide the appropriate calling object or use JavaScript's bind API to associate an implicit calling object with the method.

Now you must specify the target for the method call just as you do in all other browsers. So while this code works in Windows Internet Explorer 8 and earlier:

var d = document.writeln;
d("<script language=VBScript>");

Now it fails in Internet Explorer 9 just as it fails in all other browsers. An easy fix for this issue is to use the call method (a property of all functions) to explicitly provide the appropriate calling object:

d.call(document, "<script language="VBScript">”);

The long term fix for this is to use JavaScript's bind API to associate an implicit calling object with the method. This is done as follows (again, drawing on the previous example):

var d = document.writeln.bind(document);
d("<script language=VBScript>"); // Now this is OK.