什么时候应该选择原型继承与功能继承? [英] When should one choose prototypal inheritance vs functional inheritance?

查看:55
本文介绍了什么时候应该选择原型继承与功能继承?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读 JavaScript:The Good Parts 我现在正在第5章:继承。

I've been reading through JavaScript: The Good Parts and I'm currently on "Chapter 5: Inheritance."

据我所知,使用函数继承是首选,因为它允许隐私对象的属性和变量,同时仍然允许使用对象外部的方法调用它们。但是,看起来原型继承有一个优点,因为你可以很容易地创建一个原型对象(这使得理解对象是什么,对我来说,更具体一点)。

From what I understand, using functional inheritance is preferred because it allows privacy for the properties and variables of an object while still allowing them to be called using methods outside of the object. However, it does seem like there is an advantage for prototypal inheritance because you can create a prototype object fairly easily (which makes understanding what the object is, to me, a little more concrete).

我应该何时选择其中一个?我应该尽可能总是使用功能继承吗?或者我可以遵循更好的指导方针来做出这个决定吗?

When should I choose one over the other? Should I always use functional inheritance whenever possible? Or are there "better" guidelines that I can follow to make that determination?

推荐答案

我见过很少使用的代码功能技术作为继承的主要形式。我见过的绝大多数都使用了原型继承。它实现起来快速而简单,对JavaScript来说似乎最自然。

I've seen very little code that uses functional techniques as the primary form of inheritance. The vast majority I've seen uses prototypal inheritance. It's fast and easy to implement, and seems most natural to JavaScript.

这并不是说永远不应该使用功能继承,但我认为你会发现原型更多对于大多数应用来说已经足够了。

That's not to say that functional inheritance should never be used, but I think you'll find prototypal more than sufficient for most applications.

让我们不要忘记你仍然可以在原型继承中使用一些功能技术,比如为每个对象提供它自己的关闭函数的版本在构造函数中的变量上。所以它不需要完全是一个或另一个。

Let's not also forget that you can still use some functional techniques within your prototypal inheritance, like giving each object it's own version of a function that closes over a variable in the constructor. So it doesn't need to entirely be one or the other.

最重要的是理解原型和函数/闭包的概念。仅此一项就可以为您提供您需要了解的信息,以便做出适当的决定。

Most important is to understand the concepts of prototypes and functions/closures. This alone will give you what you need to know in order to make appropriate decisions.

这篇关于什么时候应该选择原型继承与功能继承?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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