takeaway
To understand the principles of new in JS, you should first know arguments and apply
We’ll talk a little bit more about bind, call, apply
process
- We need to know what did we do when new
- Create a new object;
- Assign the constructor’s scope to the new object (so this refers to the new object)
- Execute the code in the constructor (add attributes to this new object)
- Returns a new object.
function New() {
// Constructor denotes the new Constructor
const Constructor = Array.prototype.shift.call(arguments)
// If the new object is not a function, TypeError is raised
if (typeofConstructor ! = ='function') throw new TypeError(`${Constructor} is not a Constructor`);
// Create an empty object target of the constructor's prototype
const target = Object.create(Constructor.prototype);
// Point the constructor's this to the empty object created in the previous step, and execute to add instance attributes to this
const result = Constructor.apply(target, arguments);
// If the previous step is an object, return target
return isObject(result) ? result : target;
}
// Simply distinguish between functions and objects
function isObject(value) {
const type = typeof value;
returnvalue ! = =null && (type === 'object' || type === 'function');
}
// Constructor -computer
function Computer(brand) {
this.brand = brand;
}
// Instance object - Kevin
const kevin = New(Computer, 'kevin');
console.log(kevin); // => Computer { brand: 'kevin' }
console.log(kevin instanceof Computer); // true
Copy the code
summary
I hope after reading this article you can have the following help:
- Learn how the constructor new works
If there are any mistakes in this article, please correct them in the comments section. If this article has helped you, please like it and follow it.
Previous content recommended
- Deep copy
- Easily understand the JS prototype prototype chain