1. What does the new operator do
The new operator creates an instance of a user-defined object type or of a built-in object with a constructor. The new keyword does the following: creates an empty simple JavaScript object (that is {}); Link this object (that is, set its constructor) to another object; Use the new object created in Step 1 as the context for this; If the function does not return an object, this is returned.
2. Simple implementation
function create(Con, ... args){
// Create an empty object
let obj = Object.create(null);
// Point the empty object to the constructor's prototype chain
Object.setPrototypeOf(obj, Con.prototype);
// obj binds to the constructor to access properties in the constructor, obj.con (args)
let result = Con.apply(obj, args);
Return if result is an object
// The new method is invalid, otherwise obj is returned
return result instanceof Object ? result : obj;
}
/ / test
function company(name, address) {
this.name = name;
this.address = address;
}
var company1 = create(company, 'yideng'.'beijing');
console.log('company1: ', company1);
Copy the code
Welcome to pay attention to my public account “front-end history robbery Road”
Reply keyword e-books, you can get nearly 12 front-end popular e-books.
Reply keywords little Red Book 4th edition, you can get the latest “JavaScript advanced Programming” (4th edition) ebook.
You can also add me to wechat. I have wooed many IT bigwigs and created a technical exchange and article sharing group. Welcome to join.
Author: Vam’s Golden Bean Road
Main area: front-end development
My wechat account is Maomin9761
Wechat public number: the front end of the road through robbery