【问题标题】:How is 'this' context set in Array.prototype.slice.call(arguments)如何在 Array.prototype.slice.call(arguments) 中设置“this”上下文
【发布时间】:2013-03-18 15:50:39
【问题描述】:

有很多问题和答案都涵盖了这种技术,但我似乎无法找到有关如何为 call() 或 apply() 设置所需的 this 上下文的答案。

我明白了

Array.prototype.slice.call(arguments)

有点等价于

arguments.slice()

arguments 被转换为正确的数组对象,但如果我尝试将此约定用于我自己的对象,则它不起作用。我试着写一个小测试这样做:

var Logger = function(){};
Logger.prototype.print = function(msg){ 
   console.log ((new Date()).getTime().toString() + msg); 
};

(function(){
   var o = {
    name: "Hi Bob!",
   };

   var l = new Logger();
   l.print(o.name); //works fine
   Logger.prototype.print.call(o.name); //calls print method, but 'msg' is undefined
}());

关于Array.prototypearguments 对象是否有什么特别之处可以让函数应用程序在没有必要上下文的情况下工作?

【问题讨论】:

标签: javascript


【解决方案1】:

slice 与您的函数之间的区别在于,slice 使用上下文 (this),而您的函数仅使用其参数。

如果你真的想在你的函数中使用call,请使用它

Logger.prototype.print.call(null, o.name);

但你不妨使用

 Logger.prototype.print(o.name);

【讨论】:

    【解决方案2】:

    您的Logger.prototype.print print 不会在任何地方使用this 变量,因此使用call() 毫无意义。您的函数期望将msg 作为参数传递。这就是l.print(o.name); 起作用的原因。

    正如你在问题中所说:

    Array.prototype.slice.call(arguments)
    

    类似于arguments.slice()。因此:

    Logger.prototype.print.call(o.name);
    

    类似于o.name.print()。如您所见,这没有任何意义。

    如果你真的想使用.call(),你可以这样:

    Logger.prototype.print.call(null, o.name);
    

    但是,正如您所见,这很愚蠢,而且比l.print(o.name); 更难阅读。

    【讨论】:

    • 根据您的回答进行了一些进一步的测试,我现在明白了。 http://jsbin.com/iwaric/1/edit 。所以arguments 参数实际上会成为slice() 的上下文,当不带参数调用它时会返回原始数组的副本。
    • @mastaBlasta:是的,这行得通。如您所见,.call() 所做的只是允许您在函数内部更改this(如果已使用)。在你的情况下,我建议坚持使用l.print(o.name);
    • 我实际上并没有这个用处。我只是在阅读其他一些使用 Array.prototype.slice.call(arguments) 的代码,然后继续寻找 call() 如何处理看起来像“数组”的参数。回想起来,答案很明显——上下文只是一个对象!!
    • @mastaBlasta: Array.prototype.slice 循环遍历对象,就好像它是一个数组一样。如果您发送给 call 的对象没有 .length 属性(和相应的数字属性),Array.prototype.slice.call 将不起作用。
    猜你喜欢
    • 2015-10-16
    • 2020-12-11
    • 2017-06-17
    • 2012-02-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-01
    • 2022-01-11
    相关资源
    最近更新 更多