Home > Web Front-end > JS Tutorial > The implementation principle and rewriting method of NEW in JS

The implementation principle and rewriting method of NEW in JS

php中世界最好的语言
Release: 2020-02-27 14:19:05
forward
3472 people have browsed it

The new operator in JavaScript creates an instance of a user-defined object type or an instance of a built-in object with a constructor. This article will introduce to you the implementation principle and rewriting method of NEW.

The implementation principle and rewriting method of NEW in JS

When it comes to new, it will definitely be associated with classes and instances, such as:

function Func() {
    let x = 100;    
    this.num = x +}
let f = new Func();
Copy after login

In the above code, we first create a function. If In object-oriented terms, an instance of the Function class is created. If the function is executed directly, it is an ordinary function. If it is executed with new, the function is called a custom class.

If a normal function is executed, it will do several things as follows:

  • Form a new execution context EC (Execution Context execution environment)

  • Form an AO (Activation Object) variable object, initialize arguments and formal parameter assignment

  • Initialize the scope chain

  • Code execution

If it is a new function execution, it has both the ordinary function execution side and its own unique things:

  • Create an object by default, and this object is an instance of the current class

  • Declare its this pointer and let it point to this newly created instance

  • No matter whether it writes return or not, the newly created instance will be returned. There is a special point here. If the user returns the content himself and the value returned is a reference type value, then The default returned instance will be overwritten, and the returned value will no longer be an instance of the class.

console.log(f);  //=>{num:200}
//f是Func这个类的实例 
//相当于给创建的实例对象新增一个num的属性 obj.num=200 (因为具备普通函数执行的一面,所以只有this.xxx=xxx才和创建的实例有关系,此案例中的x只是AO中的私有变量)

console.log(f instanceof Func); //=>TRUE instanceof用来检测某一个实例是否属于这个类
Copy after login

Every time new comes out, it is a new instance. Object

console.log(f === f2); //=>false
Copy after login

Now that we know what new has done, let’s try new again:

/* 
 * 内置NEW的实现原理 
 * @params
 *    Func:操作的那个类
 *    ARGS:NEW类的时候传递的实参集合
 * @return
 *    实例或者自己返回的对象
 */
function _new(Func, ...args) {
    //默认创建一个实例对象(而且是属于当前这个类的一个实例)
    let obj = {};

    //也会把类当做普通函数执行
    //执行的时候要保证函数中的this指向创建的实例
    let result = Func.call(obj, ...args);

    //若客户自己返回引用值,则以自己返回的为主,否则返回创建的实例
    if ((result !== null && typeof result === "object") || (typeof result === "function")) {
        return result;
    }
    return obj;
}
Copy after login

Let’s try it:

let f3 = _new(Func);
console.log(f3); // =>{num: 200}
Copy after login

Let’s continue testing:

Func.prototype.log = function () {
    console.log('ok');
}

let f4 = _new(Func);
f4.log(); //=>Uncaught TypeError: f4.log is not a function
Copy after login

In other words, the instance of the method on the Func prototype cannot be called, we still need to modify it:

/* 
 * 内置NEW的实现原理 
 * @params
 *    Func:操作的那个类
 *    ARGS:NEW类的时候传递的实参集合
 * @return
 *    实例或者自己返回的对象
 */
function _new(Func, ...args) {
    //默认创建一个实例对象(而且是属于当前这个类的一个实例)
    // let obj = {};
    let obj = Object.create(Func.prototype);

    //也会把类当做普通函数执行
    //执行的时候要保证函数中的this指向创建的实例
    let result = Func.call(obj, ...args);

    //若客户自己返回引用值,则以自己返回的为主,否则返回创建的实例
    if ((result !== null && typeof result === "object") || (typeof result === "function")) {
        return result;
    }
    return obj;
}
Copy after login

This should be enough.

let f6 = _new(Func);
f6.log(); //=>ok
Copy after login

This article comes from the js tutorial column, welcome to learn!

The above is the detailed content of The implementation principle and rewriting method of NEW in JS. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:cnblogs.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template