VBScript真是一门很笨拙的语句,End就End,还要说明是End,与同样使用end收尾的ruby霄壤之别!
Class User private [_name] Public Property Let name(neo) [_name] = neo End Property Public Property Get name() '没有return 语句, 用“属性名 + 等号+ 值”实现 name = "我的名字叫 " & [_name] End Property End Class Dim a Set a = New User a.name = "司徒正美" MsgBox(a.name)
看JS相同的实现
function User(name){ var _name = name; this.__defineSetter__("name", function(val){ _name = val; }) this.__defineGetter__("name", function(){ return "我的名字叫做 "+_name; }) } var user = new User("司徒正美"); alert(user.name) //或者 function Field(val){ this.value = val; } Field.prototype = { get value(){ return this._value +"!!"; }, set value(val){ this._value = val; } }; var field = new Field("nick"); alert(field.value)
VBScript没有构造器的概念,但它有个奇怪的Default语句,一个类只允许一个。当类实例化后,它能直接像函数一直调用。
Class MyClass Public Default Function SayHello(name) '神奇的Default语句 SayHello = "Hello, " & name End Function End Class Set o = New MyClass MsgBox o("demon") '像函数一样调用实例,它明明应该是一个对象
所有VBScript类都自动支持两个事件:Class_Initialize与Class_Terminate,用于初始化与被销毁时
Class TestClass ' Setup Initialize event. Private Sub Class_Initialize MsgBox("初始化") End Sub ' Setup Terminate event. Private Sub Class_Terminate MsgBox("被销毁") End Sub End Class ' Create an instance of TestClass. Set X = New TestClass ' Destroy the instance. Set X = Nothing
有了 Default 关键字之后,我们可以模拟实现构造函数的功能:
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