Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

关于bind & new 的理解 #1

Open
wangliang1124 opened this issue Feb 28, 2018 · 0 comments
Open

关于bind & new 的理解 #1

wangliang1124 opened this issue Feb 28, 2018 · 0 comments

Comments

@wangliang1124
Copy link
Owner

wangliang1124 commented Feb 28, 2018

先看MDN上bind的polyfill

`

if (!Function.prototype.bind) {
  Function.prototype.bind = function(oThis) {
    if (typeof this !== 'function') {
      throw new TypeError('Function.prototype.bind - what is trying to be bound is not callable');
    }

    var aArgs   = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP    = function() {},
        fBound  = function() {
          return fToBind.apply(this instanceof fNOP
                 ? this
                 : oThis,
                 aArgs.concat(Array.prototype.slice.call(arguments)));
        };

    if (this.prototype) {
      // Function.prototype doesn't have a prototype property
      fNOP.prototype = this.prototype; 
    }
    fBound.prototype = new fNOP();

    return fBound;
  };
}

`
接着,这是《你不知道的JavaScript》中的一段代码,这段代码怎么执行的?

`

function foo(something) {
  this.a = something;
}
var obj1 = {};
var bar = foo.bind( obj1 ); 
bar( 2 );
console.log( obj1.a ); // 2
var baz = new bar(3);
console.log( obj1.a ); // 2
console.log( baz.a ); // 3

`

首先看这一句var bar = foo.bind( obj1 ); , bind被foo调用(bind的执行环境是foo),因此polyfill中fToBind = this,的this就是foo,模拟过程如下:

`

var obj1 = {'__proto__': foo.prototype}
fNOP.apply(obj1, arguments);
fbound.prototype = obj1;
bar = fBound;

`

然后看这一句var baz = new bar(3);,模拟如下:

`

// bar.prototype === obj1, obj1 === { __proto__: foo.prototype }, foo.prototype === { constructor: foo, __proto__} 
var obj2 = { __proto__: bar.prototype }  //  obj2 = { __proto__: {__proto__: { constructor: foo, __proto__} } }
bar.apply(obj2, arguments)
baz = obj2

`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant