我正在使用Windows Script Host VBScript,我很好奇VBScript是否能够添加/删除JScript等属性。
例如:
var global = this;
var test = function() {
if ('greeting' in global) {
WScript.echo (
'global has property named greeting with value: ' +
global.greeting +
'.'
);
} else {
WScript.echo('global has no property named greeting.');
}
};
test();
global.greeting = 'Hello, World!';
test();
delete global.greeting;
test();
此代码确定全局范围(JScript没有对全局范围的初始访问权限,例如浏览器中的窗口或Node.js中的全局范围,因此我必须自己查找)。
test()
函数检查全局对象是否具有名为“greeting”的键,并将其当前状态报告为输出。
代码执行初始测试以显示全局对象没有问候键,然后设置greeting属性,然后进行第二次测试以显示问候键已添加到全局对象。在此之后,将删除greeting属性并运行第三个测试以显示该键不再是全局对象的一部分。
这可以在VBScript中复制吗?
我知道VBScript有Scripting.Dictionary
对象可以用来存储这些信息,但我很好奇是否有办法用新属性挂钩现有对象并在VBScript中删除这些属性,或者如果VBScript没有与JScript的{}
构造并行,而不是Scripting.Dictionary
或类(其属性是不可变的)。
答案 0 :(得分:4)
您的具体示例可以使用以下内容进行模拟:
Set global = CreateObject("Scripting.Dictionary")
Sub test
If global.Exists("greeting") Then
WScript.Echo "global has property named greeting with value: " & _
global("greeting") & "."
Else
WScript.Echo "global has no property named greeting."
End If
End Sub
test
global("greeting") = "Hello, World!"
test
global.Remove("greeting")
test
但一般来说,VBScript中不支持修补对象,甚至是常规继承。扩展类所能做的最好的事情是将它包装在你自己的类中:
Class MyClass
Private nested_
Public Sub Class_Initialize
Set nested_ = CreateObject("Some.Other.Class")
End Sub
Public Function Foo(val) 'wrapped method
Foo = nested_.Foo(val)
End Sub
Public Function Bar(val) 'patched method
x = nested_.Bar(val)
Bar = x * 42
End Sub
End Class