如何在bulit apply方法中创建自定义javascript 让我们考虑这个例子:-< /P> function X(){ var Y = function(arg1,arg2){ document.write(arguments.length); document.write(arg2); }; Y(arguments); } x(1,2,3,4,5); /*Outputs 1 and undefined respectively. Because here i am actually passing an array like-object to Y. */

如何在bulit apply方法中创建自定义javascript 让我们考虑这个例子:-< /P> function X(){ var Y = function(arg1,arg2){ document.write(arguments.length); document.write(arg2); }; Y(arguments); } x(1,2,3,4,5); /*Outputs 1 and undefined respectively. Because here i am actually passing an array like-object to Y. */,javascript,Javascript,通过使用apply here,我得到了想要的结果。 function X(){ var Y = function(arg1,arg2){ document.write(arguments.length); document.write(arg2); }; Y.apply(this,arguments); } x(1,2,3,4,5) //outputs 5 and 2 我想创建一个类似ap

通过使用apply here,我得到了想要的结果。

function X(){
     var Y = function(arg1,arg2){
              document.write(arguments.length);
              document.write(arg2);
              };
     Y.apply(this,arguments);
}

x(1,2,3,4,5) //outputs 5 and 2
我想创建一个类似apply的方法,它接受一个参数数组,并通过将参数作为单独的参数值传递来调用该函数

比如:


您想改用call方法。您描述的是call方法和apply方法的混合;您希望能够单独提供参数,但可以将它们作为数组提供给函数。据我所知,目前还不存在该函数,使用最初的apply/call或使用javascript对象将参数传递到函数中会更容易。

给出以下代码:

var arr=[1,2,3,4];
Y.apply_like_method(arr);
//and returns like Y(1,2,3,4)
要实现这一目标:

Function.prototype.apply_like_method = function(args) {
    return this.apply(this, args);
}
免责声明:仅供说明


换言之,使用eval时,除了大便和咯咯笑之外,没有其他方法可以解决
.apply()

function myApply(fun, ar){
  var i, r = [];
  for(i=0; i<ar.length; ++i)
    r[i] = 'ar['+i+']';
  eval('fun('+r.join(',')+');');
}
函数myApply(乐趣,ar){
var i,r=[];

对于(i=0;我真的不明白这个问题……为什么你不能直接使用
apply
?@JamesAllardice我可以,但我只想知道这个apply方法是如何编码的。@RobinsGupta:它不是用JavaScript实现的。除了
.apply()
afaik..如果您使用Product作为构造函数,为什么要添加return语句?我认为,您的答案与问题无关。正如我所指出的,这是一个MDN示例。他希望使用call/apply hybrid。
function myApply(fun, ar){
  var i, r = [];
  for(i=0; i<ar.length; ++i)
    r[i] = 'ar['+i+']';
  eval('fun('+r.join(',')+');');
}