1

下面是用于 JS 绑定的 ES5 垫片。我不明白 self .apply 在绑定函数中。我知道如何使用 apply 方法,但是在这种情况下self指向哪里?它应该是一个
函数,但这里self看起来像一个对象。

if ( !Function.prototype.bind ) {

       Function.prototype.bind = function( obj ) {

        var slice = [].slice,
        args = slice.call(arguments, 1),
        self = this,

        nop = function () {},

        bound = function () {
        return self.apply( this instanceof nop ? this : ( obj || {} ), // self in this line is supposed  
        to // represent a function ?
        args.concat( slice.call(arguments) ) );
        };

        nop.prototype = self.prototype;
        bound.prototype = new nop();
        return bound;
        };
  }
4

2 回答 2

2

self正在您列出的填充程序中使用,以适应this随着范围更改而更改的事实。在 Function.prototype.bind 函数的直接范围内,this将引用调用绑定函数的对象。

一旦进入嵌套bound函数的作用域就发生了this变化;所以作者self = thisbind函数内赋值,允许调用this时的值通过词法作用域(闭包)bind保持对函数可用。bound

JavaScript 中的作用域会变得相当复杂。有关详细说明,请查看这篇文章。

你想知道的关于 JavaScript 作用域的一切。

于 2013-12-31T20:39:54.357 回答
-1

请记住,在 javascript 中,几乎所有内容都是对象。

所以你有它:

自我 = 这个

所以,self不代表任何东西,self实例。

于 2012-05-18T14:12:56.780 回答