Expand Minimize
7 out of 9 rated this helpful - Rate this topic

Calling a Method with a Function Pointer without ".call" or ".bind"

Previous versions of Windows Internet Explorer supported caching a pointer to a method and then using the cached pointer to call the method. This support was removed in Windows Internet Explorer 9 to increase 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>");

In 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.

Symptom

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

Resolution

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.

Examples

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.

 

 

Build date: 9/28/2012

Did you find this helpful?
(1500 characters remaining)

Community Additions

ADD
© 2013 Microsoft. All rights reserved.