JavaScript中的Prototypal vs Functional OOP [英] Prototypal vs Functional OOP in JavaScript

查看:119
本文介绍了JavaScript中的Prototypal vs Functional OOP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

编写面向对象脚本时每种类型/方法的优缺点是什么?

What are the pros and cons of each type/approach in writing Object Oriented scripts?

就个人而言,我发现闭包(功能性方法)是一种方法封装状态更自然,也许更优雅。但是,我听说在JavaScript实现中这种闭包的使用速度较慢。

Personally, I have found closures (functional? approach) as a way to encapsulate state more natural and perhaps more elegant. I, however, have heard that this use of closures is slower in JavaScript implementations.

我至少想知道原型方法最合适的地方。

I would at least like to know where a prototypal approach would be most appropriate.

推荐答案

功能风格(大多数人称之为传统OOP):


  • 优势: OOP的工作方式与每个人(或至少是Java程序员)熟悉的方式相同,包括真正的私有方法和变量

  • 缺点: Javascript不是为这种类型的OOP设计的,所以你最终会跳过大量的箍来使它工作。这些箍使调试更加困难,并且还增加了性能成本(虽然确切的成本取决于你使用它们的方式/数量)。

  • Advantage: OOP that works the way everyone (or at least Java programmers) is/are familiar with, including "truly" private methods and variables
  • Disadvantage: Javascript wasn't designed for this type of OOP, so you wind up jumping through a lot of hoops to make it work. These hoops make debugging more difficult, and also add a performance cost (although the exact cost will depend on how/how much you use them)

原型样式:


  • 优势:这是Javascript的方式OOP专为。

  • 缺点:这不是你习惯的(除非你有其他原型继承语言的背景)

  • Advantage: It's OOP in the way Javascript was designed for.
  • Disadvantage: It's not what you're used to (unless you have a background in other protoype inheritance languages)

因此,如果性能对您来说不是一个大问题,并且您只熟悉传统的OOP ...那就去吧(Pro Javascript Design Patterns,来自APress ,有一个很好的模式)。但是,如果性能很重要或者您担心额外的抽象层会使调试复杂化,请花点时间阅读原型继承的工作原理;你会成为一个更好的Javascript程序员。

So if performance isn't a huge issue for you and you're only familiar with traditional OOP ... go for it (Pro Javascript Design Patterns, from APress, has a good pattern for this). But if performance matters or you're worried about the extra layer of abstraction complicating your debugging, take the time to read up on how prototype inheritance works; you'll be a better Javascript programmer for it.

P.S。如果您担心没有原型样式的真正私人方法,我强烈建议阅读:
http://snook.ca/archives/javascript/no-love-for-module-pattern
它提供了一个很好的解释为什么真正的私人 成员实际上是一件坏事(至少在大多数JS开发环境中都是如此)。

P.S. If you're worried about not having true "private" methods with the prototype style, I strongly recommend reading: http://snook.ca/archives/javascript/no-love-for-module-pattern It provides a great explanation of why true "private" members are actually a bad thing (at least in most JS development environments).

这篇关于JavaScript中的Prototypal vs Functional OOP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆