简体   繁体   English

为什么对Function.prototype函数的引用不起作用

[英]Why do references to Function.prototype functions not work

Why does the second case not working? 为什么第二种情况不起作用?

// 1. works
Object.prototype.hasOwnProperty.call({a:1}, 'a');

// 2. does not work
var hasProp = Object.prototype.hasOwnProperty.call;
hasProp({a:1}, 'a');

http://jsbin.com/ramenaxame/2/edit?js,console http://jsbin.com/ramenaxame/2/edit?js,console

Note that all functions share the same call method, inherited from Function.prototype . 请注意,所有函数共享相同的call方法,继承自Function.prototype

Object.prototype.hasOwnProperty.call === Function.prototype.call // true

When you call call on a function, that function becomes the this value for call , so call can call the function. 当你在函数上调用call时,该函数成为callthis值,所以call可以调用该函数。 This is the case of your first code, which works. 您的第一个代码就是这种情况。

However, in your second code, you don't call call as a method of an object. 但是,在第二个代码中,不要将call作为对象的方法。 Therefore, its this value will be undefined in strict mode, or the global object in non-strict mode. 因此,它的this值在严格模式下是undefined ,或者在非严格模式下是全局对象。 Neither undefined nor the global object are callable, so call will throw. undefined和全局对象都不可调用,所以call会抛出。

In fact, your code is equivalent to 实际上,您的代码相当于

var hasProp = Function.prototype.call;
hasProp({a:1}, 'a');

As you can see, there is no reference to hasOwnProperty , so it can't work. 如您所见,没有对hasOwnProperty引用,因此它无法工作。

You can fix that using call to call call with hasOwnProperty as the this value: 您可以修复使用call呼叫callhasOwnPropertythis值:

var call = Function.prototype.call;
call.call(Object.prototype.hasOwnProperty, {a:1}, 'a');

But a better idea would be creating a new function that behaves like call but has its this value bound to hasOwnProperty . 但是,一个更好的想法是创建一个行为像一个新的函数call ,但有this势必值hasOwnProperty You can use bind to achieve this: 您可以使用bind来实现此目的:

var hasProp = Function.prototype.call.bind(Object.prototype.hasOwnProperty);
hasProp({a:1}, 'a');

您可以通过这种方式分离方法以使其工作:

var hasProp = Function.call.bind(Object.prototype.hasOwnProperty)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM