Simulate the 'new' operator in JavaScript

后端 未结 4 720
别跟我提以往
别跟我提以往 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:23

    Here is an alternative to using the __proto__ approach. Its in line with how the OP initially started out...

    function New(fn) {
        var newObj = Object.create(fn.prototype);
        return function() {
            fn.apply(newObj, arguments);
            return newObj;
        };
    }
    

    This is a much cleaner way of doing it, and it passes prototype chain tests too.

提交回复
热议问题