Understanding the difference between Object.create() and new SomeFunction()

后端 未结 11 2506
失恋的感觉
失恋的感觉 2020-11-22 05:05

I recently stumbled upon the Object.create() method in JavaScript, and am trying to deduce how it is different from creating a new instance of an object with

11条回答
  •  再見小時候
    2020-11-22 05:52

    This:

    var foo = new Foo();
    

    and

    var foo = Object.create(Foo.prototype);
    

    are quite similar. One important difference is that new Foo actually runs constructor code, whereas Object.create will not execute code such as

    function Foo() {
        alert("This constructor does not run with Object.create");
    }
    

    Note that if you use the two-parameter version of Object.create() then you can do much more powerful things.

提交回复
热议问题