Home > Web Front-end > JS Tutorial > How does JavaScript simulate the implementation of the new keyword? (with code)

How does JavaScript simulate the implementation of the new keyword? (with code)

不言
Release: 2018-11-12 16:34:26
forward
2830 people have browsed it

The content of this article is about how JavaScript simulates the implementation of the new keyword? (Attached is the code), which has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

I’ve been too busy with work recently, and I haven’t updated my blog for almost two weeks. I always feel that there are some things waiting for me to do. Although the work content has greatly improved me, I always feel that I keep walking with my head buried. Occasionally, I need to raise my head and see if my current situation is out of line with my expectations, so I still choose to go to Starbucks to write some words on weekends.

Today we record the simulation implementation of the new keyword in JavaScript. Before we simulate a certain language behavior, we should think about what this behavior does. Through practice, we can finally master the knowledge points better. This is why many interview questions ask about simulation implementations, in order to examine the depth of the candidate's knowledge.

function Person(name) {
    this.name = name;
}
var person = new Person('jayChou');
typeof(person)  // "object"
person instanceof Person  // true
person.__proto__ === Person.prototype  // true
person.constructor === Person  //  true
person.constructor === Person.prototype.constructor  // true
Copy after login

As you can see from the above:

  1. new creates and returns a new object, which is an instance of the constructor

  2. The constructor attribute of an object instance is actually the constructor attribute of the prototype object of the constructor

  3. The __proto__ of the object instance is associated with the prototype object of the constructor

The above content contains knowledge about prototype objects and prototype chains in JavaScript. Students who are not clear enough can check my previous blog.

Since new is a keyword of JS, we cannot implement the keyword, but we can simulate the behavior of the new keyword through functions.

1. Basic idea

If we know what the new keyword does, then we have the basic idea for simulation implementation.

/**
 * 模拟实现 JavaScript new 操作符
 * @param  {Function} constructor [构造函数]
 * @return {Object|Function|Regex|Date|Error}      [返回结果]
 */
function mockNew() {
    // 创建一个空对象
    let resultObj = new Object();

    // 取传入的第一个参数,即构造函数,并删除第一个参数。
    let constructor =  Array.prototype.shift.call(arguments);
    
    // 类型判断,错误处理
    if(typeof constructor !== "function") {
        throw("构造函数第一个参数应为函数");
    }
    
    // 绑定 constructor 属性
    resultObj.constructor = constructor;
    
    // 关联 __proto__ 到 constructor.prototype
    resultObj.__proto__ = constructor.prototype;
    
    // 将构造函数的 this 指向返回的对象
    constructor.apply(resultObj, arguments);
    
    // 返回对象
    return resultObj;
}

function Person(name) {
    this.name = name;
}


var person = mockNew(Person, "jayChou");

console.log(person);

// constructor: ƒ Person(name)
// name: "jayChou"
// __proto__: Object
Copy after login

The basic idea is correct! So we completed the preliminary simulation of the new keyword. Friends can type it by themselves to see if they can understand each sentence of code.

2. Processing return values

Constructors are also functions, with different types of return values. Sometimes the constructor will return the specified object content, so this part needs to be processed.

/**
 * 模拟实现 JavaScript new 操作符
 * @param  {Function} constructor [构造函数]
 * @return {Object|Function|Regex|Date|Error}      [返回结果]
 */
function mockNew() {
    // 创建一个空对象
    let emptyObj = new Object();

    // 取传入的第一个参数,即构造函数,并删除第一个参数。
    // 关于为什么要用 Array.prototype.shift.call 的形式,见之前的博客文章 《JavaScript之arguments》
    let constructor =  Array.prototype.shift.call(arguments);
    
    // 类型判断,错误处理
    if(typeof constructor !== "function") {
        throw("构造函数第一个参数应为函数");
    }
    
    // 绑定 constructor 属性
    emptyObj.constructor = constructor;
    
    // 关联 __proto__ 到 constructor.prototype
    emptyObj.__proto__ = constructor.prototype;
    
    // 将构造函数的 this 指向返回的对象
    let resultObj = constructor.apply(emptyObj, arguments);
    
    // 返回类型判断, 如果是对象,则返回构造函数返回的对象
    if (typeof resultObj === "object") {
        return resultObj
    }
    
    // 返回对象
    return emptyObj;
}

function Person(name) {
    this.name = name;
    return {
        name: this.name,
        age: 40
    }
}


var person = mockNew(Person, "jayChou");

console.log(person);

// {name: "jayChou", age: 40}
// age: 40
// name: "jayChou"
// __proto__: Object
Copy after login

When the return value returns a custom object, the simulated new function returns the custom object.

Summary

The significance of the JavaScript new keyword is to allow an ordinary function to generate a new object and associate the __proto__ of the object instance to the prototype object of the function.

Some places in this article require some pre-knowledge, but overall it is relatively easy to understand.

The above is the detailed content of How does JavaScript simulate the implementation of the new keyword? (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.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