【问题标题】:Reference to Object.prototype.toString.call resulting in 'TypeError: undefined is not a function'引用 Object.prototype.toString.call 导致 'TypeError: undefined is not a function'
【发布时间】:2015-02-23 15:23:32
【问题描述】:

我遇到了不寻常的情况。我存储了对Object.prototype.toString.call 的引用,以尝试创建快捷方式,将其作为分配的变量调用会导致TypeError,而每次都直接调用它不会。

谁能解释实际发生的事情,而不是我认为我正在做的事情?

var toString = Object.prototype.toString.call;
toString({}); //Uncaught TypeError: undefined is not a function

而以下工作:

var toString = Object.prototype.toString;
toString.call({});

非常感谢。

【问题讨论】:

标签: javascript reference prototype this typeerror


【解决方案1】:

当你在做的时候

var obj = {};
console.log(obj.toString());

toString 函数中的thisThisBinding 指的是obj。换句话说,this = obj。这就是它起作用的原因。方法toString 使用this,而不是参数。

当您执行 var toString = Object.prototype.toString.call; 时,this 引用会丢失,这实际上是在方法中执行的。

但在第二种情况下,您只是存储函数引用,通过使用Function.call,您将this 设置为{},这就是它起作用的原因,因为this 引用设置为Object 被执行。

【讨论】:

    【解决方案2】:

    第一种情况是对未绑定Function.call的引用,所以

    var unbound_call = Object.prototype.toString.call;
    unbound_call({});
    // equivalent
    Function.prototype.call.call(undefined, {}); // There is no `this`, so undefined
    // equivalent
    undefined.call({});
    

    当然,这毫无意义,因为 call 期望在 Function 对象上调用,而不仅仅是任何对象。

    应该注意的是,Firefox 会告诉您这种不兼容性:

    TypeError: Function.prototype.call 在不兼容的未定义上调用

    (好吧,undefined 仍然具有误导性)

    至于你的第二个版本:

    var unbound_toString = Object.prototype.toString.call;
    unbound_toString.call({})
    // equivalent
    Object.prototype.toString.call({}); // D'OH
    // equivalent
    {}.toString();
    

    所以这是一个合理的呼叫并且有效。

    【讨论】:

      猜你喜欢
      • 2012-06-05
      • 1970-01-01
      • 2015-06-24
      • 2021-06-21
      • 1970-01-01
      • 2022-11-29
      • 2014-08-15
      • 2015-01-14
      • 2014-07-06
      相关资源
      最近更新 更多