I know how new operator works, it follows 5 steps:
- Create a new blank object, let's call the new object as
obj - link prototype object of constructor function to the property
__proto__of the new object - bind
thisto the newly created objectobj - if the function doesn't return an object, it will return
this(newly created object), otherwise, it will return the value inreturnstatement of the function
and I know arrow function ()=>{} does not have its own bindings to this, so it will find this in the outer lexical environment.
Here is my questions:
Question 1: Why the results of person() and foo() are different? ( the former is Person Object, the latter is Window Object )
function Person() {
const bar = () => {
console.log(this);
};
return bar;
}
const person = new Person();
person(); // Person
const foo = Person();
foo(); // Window
Question 2: After the new + Person() finish executing and return arrow function bar, does bar have closure of this which belongs to the scope of constructor function Person? and, will this which binded to the newly create object obj instead of the variable bar be destoryed?
2.1 If bar(assigned to person) have not closure of this, then how person() find this when executing?
2.2 If this have not be saved and not be returned to person, why console.log(this) return Object Person?
for example:
function Person() {
let x = 10;
const bar = () => {
console.log(this);
console.log(x);
}
return bar;
}
const person = new Person();
person(); // Person,Closure: {x: 10};
const foo = Person();
foo(); // Window, Closure: {x: 10};
person() have to find variable x in the outer lexical environment (lexical environment of function Person), so it have closure of x.
Since person() have to find this in the outer lexical environment too, will it have closure of this which in the scope of function Person?
If the anwser of the question is true, then person() will find this which bind to obj(Person Object) created by new key word.
And foo have closure of this which delivered by Person and binded to Window Object.
I think it's the only way to explain why person() have result Person, and foo() has result Window