Using “Object.create” instead of “new”

后端 未结 15 2357
隐瞒了意图╮
隐瞒了意图╮ 2020-11-22 06:08

Javascript 1.9.3 / ECMAScript 5 introduces Object.create, which Douglas Crockford amongst others has been advocating for a long time. How do I replace new

15条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-22 06:56

    I think the main point in question - is to understand difference between new and Object.create approaches. Accordingly to this answer and to this video new keyword does next things:

    1. Creates new object.

    2. Links new object to constructor function (prototype).

    3. Makes this variable point to the new object.

    4. Executes constructor function using the new object and implicit perform return this;

    5. Assigns constructor function name to new object's property constructor.

    Object.create performs only 1st and 2nd steps!!!

    In code example provided in question it isn't big deal, but in next example it is:

    var onlineUsers = [];
    function SiteMember(name) {
        this.name = name;
        onlineUsers.push(name);
    }
    SiteMember.prototype.getName = function() {
        return this.name;
    }
    function Guest(name) {
        SiteMember.call(this, name);
    }
    Guest.prototype = new SiteMember();
    
    var g = new Guest('James');
    console.log(onlineUsers);
    

    As side effect result will be:

    [ undefined, 'James' ]
    

    because of Guest.prototype = new SiteMember();
    But we don't need to execute parent constructor method, we need only make method getName to be available in Guest. Hence we have to use Object.create.
    If replace Guest.prototype = new SiteMember();
    to Guest.prototype = Object.create(SiteMember.prototype); result be:

    [ 'James' ]
    

提交回复
热议问题