为什么?嗯,正如您可能知道的那样,具有Chakra的主机默认情况下未启用。根据
MSDN文档:
引用:
从JScript 5.8开始,默认情况下,JScript脚本引擎支持语言特性集,就像在版本5.7中存在的那样。这是为了保持与早期版本的引擎的兼容性。要使用版本5.8的完整语言功能集,Windows Script接口主机必须调用IActiveScriptProperty :: SetProperty。
据我所了解,这意味着您必须编写自己的自定义脚本执行主机来使用Chakra评估现有代码。
尽管这种方法听起来很吸引人,但更容易的方法是从其他地方克隆所需的任何对象和方法。通过将
htmlfile
COM对象强制转换为兼容模式,可以公开当前脚本主机无法使用的对象和方法。
// classic WSH JScript version
var htmlfile = new ActiveXObject('htmlfile'), JSON
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
htmlfile.close(JSON = htmlfile.parentWindow.JSON);
完成了!现在你可以使用 JSON.parse()
或 JSON.stringify()
,而无需包含 json2.js,也无需通过调用 IActiveScript::SetProperty
来进行大量努力。
关于上面的代码片段的快速说明:在经典 JScript 中,htmlfile.write('<meta... etc />')
可以工作,但是 .NET 主机由于某种原因无法使用 write()
和 writeln()
方法。如果您切换到 .aspx 和 JScript.NET,则应改用 IHTMLDocument2_write()
和 IHTMLDocument2_writeln()
。
// JScript.NET version
var htmlfile:Object = new ActiveXObject('htmlfile'), JSON:Object = {}
htmlfile.IHTMLDocument2_write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
htmlfile.close(JSON = htmlfile.parentWindow.JSON);
我还想指出,其他更现代的ECMAscript方法可以用类似的方式导入。这里有几个其他方法的演示,
在JScript 5.7中不是本地可用的,但可以从IE9标准模式中的
htmlfile
进行克隆。将其保存为.asp扩展名并在Web浏览器中访问:
<%@ Language="JScript" %>
<h3>Output:</h3>
<textarea style="width: 100%; height: 5em"><%
var htmlfile = Server.CreateObject('htmlfile');
htmlfile.write('<meta http-equiv="x-ua-compatible" content="IE=9" />');
// expose more modern methods from htmlfile
var JSON = htmlfile.parentWindow.JSON;
String.prototype.trim = htmlfile.parentWindow.String.prototype.trim;
Array.prototype.indexOf = htmlfile.parentWindow.Array.prototype.indexOf;
Array.prototype.forEach = htmlfile.parentWindow.Array.prototype.forEach;
Object.keys = htmlfile.parentWindow.Object.keys;
htmlfile.close(); // no longer needed
// demonstrate JSON.parse() and String.trim()
var strJSON = '{ "item1": " val1 needs trimmed. " }';
var objFromJSON = JSON.parse(strJSON);
Response.Write('JSON and String.trim() demo result: ' + objFromJSON.item1.trim() + '\n');
// demonstrate Array.indexOf()
var arr = [2, 4, 6, 8, 10];
Response.Write('Array.indexOf(val) demo result: ' + arr.indexOf(4) + '\n');
// demonstrate Object.keys() and Array.forEach()
var demo = { "foo": "bar", "baz ": "qux" };
demo.getKey = function(val) {
var obj = this, result;
Object.keys(obj).forEach(function(i) {
if (obj[i] === val) result = i;
});
return result;
}
Response.Write('Object.keys(obj).forEach(fn) demo result: ' + demo.getKey('qux'));
%></textarea>
输出:
JSON and String.trim() demo result: val1 needs trimmed.
Array.indexOf(val) demo result: 1
Object.keys(obj).forEach(fn) demo result: baz