Search code examples
javascriptnew-operator

"new operator" on bound function invoked by Method and Function


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 {}
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.


Solution

  • 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())()