Reference to Object.prototype.toString.call resulting in 'TypeError: undefined is not a function'
Reference to Object.prototype.toString.call resulting in 'TypeError: undefined is not a function'
我遇到了一个不寻常的情况。我存储了对 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({});
非常感谢。
当你在做的时候
var obj = {};
console.log(obj.toString());
toString
函数中的this
或ThisBinding
指的是obj
。换句话说,this = obj
。这就是它起作用的原因。 toString
方法使用了 this
,而不是参数。
当您执行 var toString = Object.prototype.toString.call;
时,this
引用丢失,实际上是在方法中执行此操作。
但在第二种情况下,您只是存储函数引用,通过使用 Function.call
,您将 this
设置为 {}
,这就是它起作用的原因,因为 this
参考被设置为 Object
被采取行动。
第一种情况是对未绑定的引用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 called on incompatible undefined
(好的,undefined
仍然具有误导性)
至于你的第二个版本:
var unbound_toString = Object.prototype.toString.call;
unbound_toString.call({})
// equivalent
Object.prototype.toString.call({}); // D'OH
// equivalent
{}.toString();
所以这是一个声音调用并且有效。
我遇到了一个不寻常的情况。我存储了对 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({});
非常感谢。
当你在做的时候
var obj = {};
console.log(obj.toString());
toString
函数中的this
或ThisBinding
指的是obj
。换句话说,this = obj
。这就是它起作用的原因。 toString
方法使用了 this
,而不是参数。
当您执行 var toString = Object.prototype.toString.call;
时,this
引用丢失,实际上是在方法中执行此操作。
但在第二种情况下,您只是存储函数引用,通过使用 Function.call
,您将 this
设置为 {}
,这就是它起作用的原因,因为 this
参考被设置为 Object
被采取行动。
第一种情况是对未绑定的引用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 called on incompatible undefined
(好的,undefined
仍然具有误导性)
至于你的第二个版本:
var unbound_toString = Object.prototype.toString.call;
unbound_toString.call({})
// equivalent
Object.prototype.toString.call({}); // D'OH
// equivalent
{}.toString();
所以这是一个声音调用并且有效。