简体   繁体   English

一些JavaScript库是否使用了原型系统的动态方面?

[英]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. 用原型创建的JavaScript对象保持与其原型的“实时”连接,因此更改原型也会影响由此原型创建的对象。

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? 动态/动态连接的此功能是否确实在某些知名的JavaScript库或程序中使用?

EDIT: I'm not proposing JS inheritance system is flawed, I just want to understand the benefits of aforementioned feature. 编辑:我并不是说JS继承系统有缺陷,我只是想了解上述功能的好处。

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 . 我认为此功能最突出的用途是向jQuery原型(称为“插件”)动态添加方法,该方法以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. 您可以使用extend()函数使用该方法创建对象,但这会在头上敲响原型继承的概念。

It is one of the core features to have that non-static inheritance in Javascript. 在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 . 这种活力存在于修补旧版浏览器的polyfill库中,例如通过添加Array.prototype.map或从ES6添加即将推出的新功能(例如Array.prototype.find See https://github.com/paulmillr/es6-shim/ for an example. 有关示例,请参见https://github.com/paulmillr/es6-shim/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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