繁体   English   中英

这的奇怪行为

[英]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”之称。

在非严格模式下,如果以此提供的值不是对象,并且不是nullundefined ,它将被转换为对象。

因此, 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.

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