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

前端 未结 4 514
[愿得一人]
[愿得一人] 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:22

    Super late to this thread.. but I think an important distinction that needs to be made is that while constructors are just functions, the new operator invokes the function and captures the resulting object which can be useful when in a dynamic environment. It allows reference to properties and methods during execution of the constructor as well which may or may not be useful depending on the situation. If you are more concerned with having a set prototype but the object itself is more static than not, Object.create would be a better option as it is cleaner and doesn't mess with the proto-chain in unexpected ways as the new operator does.

    some simple examples..

    var Foo = function(element) {
      this.elem = element;
      $(this.elem).css('color', 'blue');
      // using the new operator here gives access to this.elem
      // immediately after that declaration is made, thus providing 
      // a comfortable dynamic system to work with 
    }
    
    var bar = new Foo(someElem);
    

    as apposed to..

    var foo = {
      elem : element,             // assume elem exists
      $(this.elem).css('color', 'blue')// in the lexical scope
    }
    
    var bar = Object.create(foo);
    // This.elem does not exist until the object is returned now
    // and the .css method call will not execute
    

    It should be slightly clearer why you would want to use one over the other, as another simple breakdown...

    Use New when you care about having a dynamic object and less about the prototype chain

    Use Object.create when you care less about being dynamic and more about having an explicit prototype chain. I will also note that objects made with Object.create can be dynamically built as well by using a method called init that you can build to assign properties based on your needs and simply call it on your freshly returned object.

    Each approach has it's ups and downs however their use cases are fairly distinct in my opinion. However, you will most likely find yourself using Object.create as most situations will call for a less dynamic situation and have more need for inheritance.

提交回复
热议问题