私はこのようなfn.bind()
のMozilla polyfillに参照してください。JavaScriptでfn.bind()をpolyfillすると、なぜ "this"のタイプをチェックする必要がありますか?
if (!Function.prototype.bind) {
Function.prototype.bind = function(oThis) {
if (typeof this !== 'function') {
// closest thing possible to the ECMAScript 5
// internal IsCallable function
throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
}
// other code omitted here...
};
}
我々はthis
の種類を確認する必要があり、なぜ私は理解していない...私たちが言う場合fn.bind()
とfn
が関数であるので、それがしますfn
が関数でない場合、fn.bind
はプロトタイプの継承によってFunction.prototype.bind
に決して到達しません。では、なぜthis
のタイプをチェックする必要がありますか?
実際に誰かが 'Function.prototype.bind'をpolyfillする必要があるのであれば、それはES5に完全に準拠していない古いJSエンジンであり、' typeof X === "関数のテストは必ず呼び出し可能。たとえば、IE8では、 'typeof alert'は' 'object" 'です。また、http://stackoverflow.com/questions/17975210 –
@ GOTO0も参照してください。実際、ホストオブジェクトは、特にIEの首の痛みです。 – Oriol