Is there any reason to use Object.create() or new in JavaScript?

前端 未结 4 486
[愿得一人]
[愿得一人] 2021-01-12 01:23

I\'ve been using the new keyword in JavaScript so far. I have been reading about Object.create and I wonder if I should use it instead. What I don\

4条回答
  •  不知归路
    2021-01-12 02:06

    So far, if you want to create an object, you can only use literals:

    var obj = {};
    

    or the Object constructor.

    var obj = Object();
    

    But none of these methods let you specify the prototype of the created object.

    This is what you can do with Object.create now. It lets you create a new object and sets the first argument as prototype of the new object. In addition, it allows you to set properties of the new object provided as second argument.

    It is similar to doing something like this (without the second argument):

    function create(proto) {
        var Constr = function(){};
        Constr.prototype = proto;
        return new Constr();
    }
    

    So if you are using a construct similar to this, this when you wanted to use Object.create.

    It is not a replacement for new. It is more an addition to make creating single objects which should inherit from another object simpler.

    Example:

    I have an object a:

    var a = {
       someFunction: function() {}
    };
    

    and I want b to extend this object. Then you can use Object.create:

    b = Object.create(a);
    b.someOtherFunction = function(){};
    

    Whenever you have a constructor function, but you only instantiate one object from it, you might be able to replace this with Object.create.

    There is general rule that applies. It depends very much on what the constructor function is doing and how you inherit from other objects, etc.

提交回复
热议问题