简体   繁体   中英

Does some JavaScript library use dynamic aspects of the prototype system?

JavaScript object created with a prototype maintains "live" connection to its prototype, so that changing the prototype also affects the objects created from it.

The semantics of the language would be much simpler if newly created object just copied everything from the prototype and then forgot about it. The actual underlying implementation could be smarter, of course.

Is this feature of live/dynamic connection actually used in some well known JavaScript library or program?

EDIT: I'm not proposing JS inheritance system is flawed, I just want to understand the benefits of aforementioned feature.

Surely. I think the most prominent use of this feature is the dynamical adding of methods to the jQuery prototype (called "plugins"), which is exposed as jQuery.fn .

I can't understand why you think "the semantics of the language would be much simpler if newly created object just copied the prototype properties". Why would that be simpler? You can create objects with that method, using a extend() function, but that knocks the concept of prototypical inheritance on the head.

It is one of the core features to have that non-static inheritance in Javascript. It is useful to modify the prototype object of already generated instances for:

  • adding features, like described above. You can load whole plugins only if you need them.
  • enhance features (sometimes). This is often used to overwrite non-standard behaviour
  • really change them (seldom). This can be used with configuration objects, which inherit from an object with the default settings. Then you can change the default settings, and they will apply to all instances (at least to them which didn't overwrite the property in question).

在最近的一次演讲中,Brendan Eich将Javascript描述为一种“目标”语言,这使得可以将诸如Jquery或CoffeeScript之类的库写在其上,库原型用于更快地公开常用的函数和方法,在javascript内部进行查看游戏原型的优秀范例的游戏框架

This dynamism is present in polyfill libraries that patch older browsers, eg by adding Array.prototype.map , or add upcoming new features from ES6, eg Array.prototype.find . See https://github.com/paulmillr/es6-shim/ for an example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM