[英]JavaScript: call vs call.bind
為什么 - 在以下代碼中 - 第3行工作和第4行沒有?
function out(x) {
console.log(x);
}
out.call(window, "bla") // outputs "bla"
out.call.bind(window, "bla")(); // throws "TypeError: object is not a function"
問題是你可能有一個拼寫錯誤:你的意思是寫出out.bind(window, "bla")()
代替,這將產生與有效的調用相同的結果。
為什么錯誤與當前代碼? out.call.bind
返回一個函數,該函數在call
window
修復this
的值。 但是, call
期望this
是一個函數,哪個window
不是。 結果是給定的錯誤。
從帶注釋的ES5規范 :
15.3.4.5 Function.prototype.bind(thisArg [,arg1 [,arg2,...]])
bind方法接受一個或多個參數thisArg和(可選)arg1,arg2等,並通過執行以下步驟返回一個新的函數對象:
1. Let Target be the this value. 2. If IsCallable(Target) is false, throw a TypeError exception. [...]
您正在按預期獲得TypeError
。
該out.call.bind
使用,很像類似out.call.call
,結果“重定向目標”的out.call
-那就是,而不是call
在被調用out
,這將是別的東西調用。 一個例子:
function foo(x) { console.log("this", this, "foo", x); }
function bar(x) { console.log("this", this, "bar", x); }
foo.call.bind(bar, window, 42)(); // "this" [window] "bar" 42
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.