Microsoft KB Archive/269258

= INFO: JScript Passes Variables by Value =

Article ID: 269258

Article Last Modified on 8/8/2007

-

APPLIES TO


 * Microsoft JScript 1.0
 * Microsoft JScript 2.0
 * Microsoft JScript 3.0
 * Microsoft JScript 4.0
 * Microsoft JScript 5.0
 * Microsoft JScript 5.5

-



This article was previously published under Q269258



SUMMARY
According to the ECMA-262 specification, Microsoft JScript passes all variables by value. Therefore, any changes that the callee makes to the variables are not reflected in the caller when it resumes execution.



MORE INFORMATION
Variables in JScript are always passed by value; passing by reference does not exist within the bounds of the language. The variables may contain a primitive value (such as a string, number, or boolean value) or they may contain a reference to an object (such as String, Number, Boolean, Object, Array, and so on), but the contents of the variables are always passed by value. In the case of objects, the value of the object cannot be changed directly, but the properties and methods of the object can be accessed. These properties and methods may, in turn, affect the value of the object, as in the case of Date.setMonth method.

To allow the callee to change the value of a variable, define an Object whose only property is the original variable and pass it instead. The following code demonstrates how to use a custom Object to allow the callee to change the value of a string: function ByRefString(strValue) { this.stringValue = strValue; }

ByRefString.prototype.toString = function {   return this.stringValue; }

function theCaller {

var str1 = new String(&quot;elk&quot;); var str2 = new ByRefString(&quot;bear&quot;); alert(str1); alert(str2); theCallee(str1, str2); alert(str1); alert(str2); }

function theCallee(param1, param2) {

param1 = &quot;moose&quot;; param2.stringValue = &quot;puffin&quot;; } In this sample code, the changes that the callee makes to the first string are not reflected in the caller, but the changes made to the Object-wrapped string are.

In addition, JScript follows the same rules when calling external components (such as Component Object Model components). In these cases, object references are passed as IDispatchEx pointers.

