定义方法
on 方法名(参数列表)
return 返回值 -- 如果无返回值可不写
end 方法名
方法的调用可在定义前或定义后
注意:
1、在方法中使用的变量都是局部变量,不能使用外部的变量,其命名也不会和外部的变量造成冲突。
set x to 1
on renameTest()
return x * 5
end renameTest
set y to renameTest()
2、局部变量的命名和外部变量的命名无冲突,修改同名的局部变量的值对外部变量无影响。例如:
set x to 1
on renameTest()
set x to 2
return 10
end renameTest
set y to renameTest()
get x --输出1
举例:获取两个数中的较大值
on getMaxNumber(a, b)
if a > b then
return a
else
return b
end if
end getMaxNumber
get getMaxNumber(2, 5)
在其他程序中调用本文件的方法
使用 of me
举例:
on test(a) --该方法是当前程序的方法,即脚本编辑器的方法
display dialog a
end test
tell application "Finder"
test("测试方法") of me -- 在Finder程序中调用,如果没有of me 会报错
end tell
调用.scpt脚本文件中的方法
步骤:
1、加载指定的.scpt脚本文件:load script 脚本文件
2、调用脚本文件中的方法
举例:
set scriptFilePath to choose file -- 选择某个脚本文件
set scriptContent to (load script scriptFilePath) -- 加载脚本文件内容
tell scriptContent
try
test("该方法为另一个脚本文件中的方法") -- 调用脚本文件中的方法
on error error_message number errorNum
display dialog "异常:" & error_message & "异常号:" & errorNum
end try
end tell
网友评论