1 Implementation principle of new
1. Create an empty object. This in the constructor refers to the empty object
2. Proto = constructor. Prototype
3. Execute the constructor method, and the properties and methods are added to the object pointed to by this
4. If no other object is returned from the constructor, return this, the new object of the created one; otherwise, return the object returned from the constructor
function myNew() {
let target = {}
// constructor
let [constructor. args] = [...arguments]; // The prototype chain association target.__proto__ =constructor.prototype; // Execute the constructor to add the property or method to target let result =constructor.apply(target, args); / / return to type the if (result && (typeof (result) = = = 'object' | | typeof (result) = = = 'function')) {return result;
}
// If the constructor returns a value that is not a reference type, but a primitive type returns a new object
return target;
}
Copy the code
2. This points to confirm
> Priority attribute access. > new foo() > foo()Copy the code
Summary: This refers to whoever calls it
Segmentation:
1. This in the global environment:
Browser environment: In the global execution environment (outside any function body) this refers to the global object Window, whether in strict mode or not; Node environment: This is the empty object {} in the global execution environment (outside any function body), whether in strict mode or not;Copy the code
2. New binding:
If the constructor does not return function or object, this refers to the new object.
```js
function Person(age){
this.age = age
}
let instance = new Person('20')
console.log(instance) // 20
```
Copy the code
The constructor returns function or object, and new Person() returns the return value of Person
```js
function Person(age){
this.age = age
return {
a: 2
}
}
let instance = new Person('20')
console.log(instance) // {a:2}
console.log(instance.age) // undefined
```
Copy the code
3. Functions are called by call, apply, or bind, so this binds to the specified object. > Special case: if the first parameter of call,apply, or bind is undefined or null, strictly this is null /undefined. The default binding rule applied in non-strict mode, this refers to the global object (node: Global, browser: Window)
4. Arrow function: Inherits this from the context binding of the arrow function