Simulate the 'new' operator in JavaScript

后端 未结 4 719
别跟我提以往
别跟我提以往 2020-11-29 08:52

I tried to simulate the \'new\' operator in JavaScript in a code like this:

Function.method(\'new\', function ( ) {
    var objPrototype = Object.create(this         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-29 09:35

    The new operator takes a function F and arguments: new F(arguments...). It does three easy steps:

    1. Create the instance of the class. It is an empty object with its __proto__ property set to F.prototype. Initialize the instance.

    2. The function F is called with the arguments passed and this set to be the instance.

    3. Return the instance

    Now that we understand what the new operator does, we can implement it in Javascript.

        function New (f) {
    /*1*/  var n = { '__proto__': f.prototype };
           return function () {
    /*2*/    f.apply(n, arguments);
    /*3*/    return n;
           };
         }
    

    And just a small test to see that it works.

    function Point(x, y) {
      this.x = x;
      this.y = y;
    }
    Point.prototype = {
      print: function () { console.log(this.x, this.y); }
    };
    
    var p1 = new Point(10, 20);
    p1.print(); // 10 20
    console.log(p1 instanceof Point); // true
    
    var p2 = New (Point)(10, 20);
    p2.print(); // 10 20
    console.log(p2 instanceof Point); // true
    

提交回复
热议问题