Advantage of using Object.create

こ雲淡風輕ζ 提交于 2019-12-04 18:34:16

问题


Similar to, but different from this question. The code below is from JavaScript: The Definitive Guide. He's basically defining an inherit method that defers to Object.create if it exists, otherwise doing plain old Javascript inheritance using constructors and swapping prototypes around.

My question is, since Object.create doesn't exist on plenty of common browsers IE, what's the point of even trying to use it? It certainly clutters up the code, and one of the commenters on the previous question mentioned that Object.create isn't too fast.

So what's the advantage in trying to add extra code in order to occasionally utilize this ECMA 5 function that may or may not be slower than the "old" way of doing this?

function inherit(p) {
   if (Object.create) // If Object.create() is defined...
      return Object.create(p); // then just use it.

   function f() {}; // Define a dummy constructor function.
   f.prototype = p; // Set its prototype property to p.
   return new f(); // Use f() to create an "heir" of p.
}

回答1:


The speed difference is not very noticeable, since by nature you probably won't be creating too many objects (hundreds, even thousands isn't what I call a lot), and if you are and speed is a critical issue you probably won't be coding in JS, and if both of the above aren't true, then I'm sure within a few releases of all popular JS engines the difference will be negligible (this is already the case in some).

In answer to your question, the reasons aren't speed-related, but because the design pattern of Object.create is favoured to the old method (for the reasons outlined in that and other answers). They allow for proper utilisation of the ES5 property attributes (which make for more scalable objects, and thus more scalable apps), and can help with inheritance hierarchies.

It's forward engineering. If we took the line of "well it isn't implemented everywhere so let's not get our feet wet", things would move very slowly. On the contrary, early and ambitious adoption helps the industry move forward, helps business decision makers support new technologies, helps developers improve and perfect new ideas and the supporting frameworks. I'm an advocate for early (but precautionary and still backward-compatible) adoption, because experience shows that waiting for enough people to support a technology can leave you waiting far too long. May IE6 be a lesson to those who think otherwise.



来源:https://stackoverflow.com/questions/7505546/advantage-of-using-object-create

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!