首页 > 代码库 > VBScript学习笔记 - 函数和子例程

VBScript学习笔记 - 函数和子例程

一、定义

1. 函数定义:

function f_add(num_in)    num_in = num_in + 1    f_add = num_inend function

用函数名来返回参数

2. 子例程定义

sub s_add(num_in)    num_in = num_in + 1end sub

子例程没有返回值

二、函数与子例程在参数传递上的差别

函数和子例程调用时可以有两种方式:在括号中指定参数,或使用不带括号的格式。

使用带括号的方式指定参数时,参数是按值传递的,函数或子例程中对参数的修改不会反映到参数中。而用不带括号的格式时,则函数或子例程中对参数值的改动都是实际发生的。

以下代码示范了这两种格式的差别:

num_out = 0wscript.echo "num before sub:", num_out用不带括号的格式调用子例程s_add num_outwscript.echo "num after sub:", num_outwscript.echo ""num_out = 0wscript.echo "num before sub():", num_out用带括号的格式调用子例程s_add(num_out)wscript.echo "num after sub():", num_outwscript.echo ""num_out = 0wscript.echo "num before function:", num_out用不带括号的格式调用函数f_add num_outwscript.echo "num after function:", num_outwscript.echo ""num_out = 0wscript.echo "num before function():", num_out用带括号的格式调用函数f_add(num_out)wscript.echo "num after function():", num_outwscript.echo ""sub s_add(num_in)    wscript.echo "num in sub", num_in    num_in = num_in + 1    wscript.echo "num in sub", num_inend subfunction f_add(num_in)    wscript.echo "num in function", num_in    num_in = num_in + 1    wscript.echo "num in function", num_in    f_add = num_inend function

输出结果如下


num before sub: 0
num in sub 0
num in sub 1
num after sub: 1

num before sub(): 0
num in sub 0
num in sub 1
num after sub(): 0

num before function: 0
num in function 0
num in function 1
num after function: 1

num before function(): 0
num in function 0
num in function 1
num after function(): 0

VBScript学习笔记 - 函数和子例程