gpt4 book ai didi

JavaScript:ActiveX 对象和 apply() 函数的问题

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:38:36 25 4
gpt4 key购买 nike

我有一个 ActiveX 对象(Master)并且想动态调用它的函数。为此,我使用 apply() 函数。但遗憾的是,InternetExplorer 告诉我一些类似的信息:“此对象不支持此方法”。有人可以提示我可以做什么吗?

(要对此进行测试,您还可以使用一个小的 flash 对象作为 Master 并调用“doSomething”而不是我特定的“Initialize”。)

function invoke(object, fnName, args)
{
return object[fnName].apply(object, args);
}

function test_it()
{
try{
Master = window.document["Master"];
}
catch(e){alert(e);}
var param = [1,"VC2"];
var ret = invoke(Master, "Initialize", param);
alert("got: "+ret);
}

为了比较,这是正在运行的 apply() 函数:

function Obj()
{
this.msg = function(a, b, c)
{
alert("msg: \n a: "+a+"\n b: "+b+"\n c: "+c);
return "hi";
}
return this;
}


function invoke(object, fnName, args)
{
return object[fnName].apply(object, args);
}

function test_it()
{
var obj = new Obj();
var ret = invoke(obj, "msg", [1, 2, 3]);
alert("got: "+ret);
}

最佳答案

IE(不仅是 IE)中的某些宿主对象(即任何非 native 对象)的问题是它们不继承自 Function.prototype (而且通常都不是来自顶级 Object.prototype )。一些可能看起来像函数的宿主对象实际上与函数无关,只是它们可以被调用。这些对象不继承自 Function.prototype 的事实意味着它们无法被识别为带有 instanceof 的函数运算符(operator);他们的构造函数没有引用 Function ;而且他们缺少所有 Function.prototype.*方法,例如 callapply .甚至它们的内部 [[Class]] 属性也可能不是“Function”的属性,因为它与任何 native 对象一样(请注意,[[Class]] 可以从 Object.prototype.toString 值的结果中推断出来)。

这实际上是意料之中的,因为不需要宿主对象来实现原生对象所做的许多事情(根据 ECMA-262,第 3 版)。完全允许宿主对象在方法调用时抛出错误(例如 hostObject.hostMethod() );或者将其作为操作数传递给标准运算符,如 delete (例如 delete hostObject.hostMethod )。如您所见,可调用主机对象也可以不从原生 Function.prototype 继承。 .

这种不可预测(但完全合规)的行为实际上是不推荐宿主对象扩充的主要原因之一。

但是回到你的call问题:)

关于这些“棘手”的 IE 宿主对象的事情是它们经常实现内部 [[Call]] 方法,并且可以调用 callapply在他们身上,尽管不是直接

这是一个可以模拟的模式 apply对没有它的对象的调用:

function f(){ return arguments };
Function.prototype.apply.call(f, null, [1,2,3]); // [1,2,3]

null当然,可以用应调用的任何上下文对象替换。

还有一个 apply 的例子对没有 call 的主机对象的调用:

// should work in IE6, even though `alert` has no `call` there
Function.prototype.call.call(alert, window, 'test');

将其应用于您的代码

// Calls Master.initialize borrowing from Function.prototype
Function.prototype.apply.call(Master.initialize, Master, [1,"VC2"]);

关于JavaScript:ActiveX 对象和 apply() 函数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1433697/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com