This article documented the implementation of the new operator.
What does the new operator do
- To create a
A new object obj. - Of this object
__proto__Property will point to the constructorPrototype prototypeThe address. - Constructor
This points to the new object objAnd,Execute constructor. - If the constructor does not return a value, or the return value is not of an object type
Object(including,Functoin.Array.Date.RegExp.Error), returns a new object obj; How does the constructor return the valueObject, returns it.
Emulate the new operator
Function newOperator(ctor) {// The first argument must be if (typeof ctor! == 'function') { throw new TypeError(ctor + 'is not a function.'); } // ES6 new.target points to newOperator.target = ctor; Var newObj = object.create (ctor. Prototype); Ctor var argsArr = [].slice.call(arguments, 1); var ctorReturnResult = ctor.apply(newObj, argsArr); // 4. If the return value is an object type, return it. Otherwise return a new object newObj var isObject = typeof ctorReturnResult === 'object' && ctorReturnResult! == null; var isFunction = typeof ctorReturnResult === 'funcion'; if (isObject || isFunction) { return ctorReturnResult; } return newObj; }Copy the code
Refer to the article
Can you simulate implementing JS’s new operator