[英]The strange behavior of this
這里有這樣的代碼,我不明白為什么輸出“ Hello”? 想法是g: bind (f, "Hello")
應該返回一個包裝函數,該函數調用函數f
在“ Hello”的上下文中。 因此, this
函數f
應該指向global object
。
function bind(func, context, args) {
var bindArgs = [].slice.call(arguments, 2); // (1)
function wrapper() { // (2)
var args = [].slice.call(arguments);
var unshiftArgs = bindArgs.concat(args); // (3)
return func.apply(context, unshiftArgs); // (4)
}
return wrapper;
}
function f() {
alert( this );
}
var user = {
g: bind(f, "Hello")
}
user.g();
不,上下文不是全局上下文,而是字符串“ Hello”。 上下文是第二個參數的bind()
函數,這樣就可以值this
當函數“f”之稱。
在非嚴格模式下,如果以此提供的值不是對象,並且不是null或undefined ,它將被轉換為對象。
因此, 該 F內將是一個String對象,其內在價值是“你好”,見ECMA-262§10.4.3 。
如果您更改:
alert( this );
到下面的內容,它顯示了對象的內部類 ,因此可以知道它是什么類型的對象:
alert(Object.prototype.toString.call(this) ); // [object String]
您將獲得[object String] 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.