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
- the console.log of
foo
inobj2.foo()
isfoo foo {}
- the console.log of
foo
inbar()()
isfoo { 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
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:
new
overrides the previously boundthis
, as documented:The reason
new bar()()
seems to behave differently is just a matter of operator precedence, because thenew
gets applied tobar()
, notbar()()
. Correct the grouping, and you’ll see the same behavior: