skip to Main Content

forgive my bad english…

I use new operator of the bound function in different way like

function foo() {
  console.log("foo", this);
}

const obj1 = { a: 1 };

function bar() {
  return foo.bind(obj1);
}

var obj2 = { b: 2, foo: bar() };

new obj2.foo(); // foo foo {}
new bar()(); // foo { a: 1 }

And

  1. the console.log of foo in obj2.foo() is foo foo {}
  2. the console.log of foo in bar()() is foo { a: 1 }

The question is I don’t understand why the this of obj2.foo() when I use new operator is an empty Object?

I have read the new operator of MDN docs , but still can’t get it.

2

Answers


  1. New doesn’t care about the [[BoundThisValue]] of bind(). It only cares about the prototype property of the object. You can still call the bound function and it will have the [[ThisValue]] bound to the object you set it to. But, when you call new(), it looks at the functions prototype, which is still an empty object.

    Essentially, you have an object that looks like this:

    foo (Function)
    [[BoundThisValue]]: obj1
    prototype: Object {} <-- new only looks at this
    
    Login or Signup to reply.
  2. new overrides the previously bound this, as documented:

    A bound function may also be constructed using the new operator if its target function is constructable. Doing so acts as though the target function had instead been constructed. The prepended arguments are provided to the target function as usual, while the provided this value is ignored (because construction prepares its own this, as seen by the parameters of Reflect.construct).

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind

    The reason new bar()() seems to behave differently is just a matter of operator precedence, because the new gets applied to bar(), not bar()(). Correct the grouping, and you’ll see the same behavior:

    new (bar())()
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search