Function Parameters Are Passed as Local Copies
This section provides a quick description of how primitive parameters and object parameters are all passed as local copies of whatever original variables store.
are passed by value and object parameters are passed by reference.
But actually, both rules are derived from a single rule: parameters are passed as local copies of
whatever original variable store:
- If a parameter is a primitive variable, a local copy of the variable is created inside the function.
Since a primitive variable contains the value directly, the local copy is a copy of the value.
Therefore we say primitive parameters are passed by value.
- If a parameter is an object variable, a local copy of the variable is created inside the function.
Since an object variable contains the reference to the object, the local copy is a copy of the reference.
Therefore we say object parameters are passed by value.
Notice that the above explanation uses these assumptions:
- A primitive variable contains the value directly.
- An object variable contains the reference to the object.
In other words, an object variable contains the address where the object is stored.
Saying that parameters are passed as local copies is actually more accurate,
because passing parameters by reference is a very different programming feature.
Taking VBScript as an example, it supports the "ByRef" keyword to allow
you to pass a function parameter as true reference for any data types, including primitive types.
A VBScript function will not create a local copy of a "ByRef" parameter.
It will use the "ByRef" parameter as an alias of the original variable.
The following VBScript code will swap the original variables by using "ByRef" parameters:
vFirst = "Dog"
vSecond = "Cat"
Call SwapByRef(vFirst, vSecond)
document.writeln(" After Sub: " & vFirst & " | " & vSecond)
Sub SwapByRef(ByRef vLeft, ByRef vRight)
vTemp = vLeft
vLeft = vRight
vRight = vTemp
you will definitely fail. See the next section for my examples.
Table of Contents
About This Book
Data Types, Variables and Expressions
Flow Control Statements
Creating, Accessing, and Manipulating Arrays
►Defining and Calling Functions
Defining Your Own Functions
Defining Your Own Functions - Example
Calling Your Own Functions - Example
Passing Parameters by Value or by Reference
►Function Parameters Are Passed as Local Copies
Function Parameters Are Passed as Local Copies - Example
Global and Local Variables - Scope Rules
Global Variables - Examples
Local Variables - Examples
Collision of Global and Local Variables - Examples
"return" Statement and Return Value
Server-Side and Client-Side Web Scripting
Introduction to Objects
Defining Your Own Object Types
Inheritance of Properties and Methods through the Prototype Object Chain
Using Functions as "Function" Objects
Introduction to Built-in Object Types
W3C's Document Object Model (DOM) Specifications
PDF Printing Version