为什么?好吧,您可能知道,具有脉轮可用的主机默认情况下没有启用它。根据MSDN documentation:
从 JScript 5.8 开始,默认情况下,JScript 脚本引擎支持 5.7 版中存在的语言功能集。这是为了保持与早期版本引擎的兼容性。要使用 5.8 版的完整语言功能集,Windows 脚本界面宿主必须调用 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 的巨大努力。
关于上面代码 sn-p 的简短说明:htmlfile.write('<meta... etc />') 在经典 JScript 中工作,但 .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 方法可以以类似的方式导入。下面是一些其他方法的演示,aren't natively available in JScript 5.7 但可以在 IE9 标准模式下从htmlfile 克隆。使用 .asp 扩展名保存此文件,在您的网络浏览器中访问它:
<%@ 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