当前位置: 移动技术网 > IT编程>脚本编程>VBScript > VBS类构造函数与Default关键字使用介绍

VBS类构造函数与Default关键字使用介绍

2017年12月08日  | 移动技术网IT编程  | 我要评论

哈虎网,236jj,弗拉西奇

其实 msdn 的 vbscript 文档中关于 function 和 sub 语句的部分提到过 default 关键字:
复制代码 代码如下:

default
used only with the public keyword in a class block to indicate that the function procedure is the default method for the class. an error occurs if more than one default procedure is specified in a class.

default 只能在 class 语句块中与 public 关键字一起使用来表明函数过程是类的默认方法。如果类中一个以上的过程被定义为 default,那么会出现错误。
一个简单的例子:
复制代码 代码如下:

class myclass
public default function sayhello(name)
sayhello = "hello, " & name
end function
end class
set o = new myclass
msgbox o("demon")

很多面向对象的语言都能使用构造函数来初始化类的对象,但是 vbs 却没有构造函数的概念,只是提供了一个类初始化事件来初始化对象:
复制代码 代码如下:

class testclass
' setup initialize event.
private sub class_initialize
msgbox("testclass started")
end sub
' setup terminate event.
private sub class_terminate
msgbox("testclass terminated")
end sub
end class
' create an instance of testclass.
set x = new testclass
' destroy the instance.
set x = nothing

虽然看起来很像构造函数,但是却不能带参数,没有办法像其他语言那样用特定的参数来初始化对象。
有了 default 关键字之后,我们可以模拟实现构造函数的功能:
复制代码 代码如下:

'author: demon
'date: 2011/09/29
'website: http://demon.tw
class rectangle
private height, width
public default function construtor(h, w)
height = h : width = w
set construtor = me
end function
public property get area
area = height * width
end property
end class
'看起来是不是很像构造函数呢
set r = (new rectangle)(6, 8)
msgbox r.area

参考链接:
原文:http://demon.tw/programming/vbs-default-keyword.html

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网