JavaScript是面向对象的吗? [英] Is JavaScript object-oriented?

查看:89
本文介绍了JavaScript是面向对象的吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

关于JavaScript是否是面向对象的语言,存在一些问题。甚至一句话,只是因为一种语言有对象并不能使它成为OO。

There have been some questions about whether or not JavaScript is an object-oriented language. Even a statement, "just because a language has objects doesn't make it OO."

JavaScript是一种面向对象的语言吗?

Is JavaScript an object-oriented language?

推荐答案

IMO(这只是一种意见) 面向对象语言的关键特性是它支持 polymorphism 。几乎所有动态语言都是这样做的。

IMO (and it is only an opinion) the key characteristic of an object orientated language would be that it would support polymorphism. Pretty much all dynamic languages do that.

下一个特征是 封装 ,这在Javascript中也很容易做到。

The next characteristic would be encapsulation and that is pretty easy to do in Javascript also.

但是在许多人的想法是 继承 (特别是实现继承),这将平衡一种语言是否有资格被称为面向对象。

However in the minds of many it is inheritance (specifically implementation inheritance) which would tip the balance as to whether a language qualifies to be called object oriented.

Javascript确实提供了一种通过原型设计继承实现的相当简单的方法这是以封装为代价的。

Javascript does provide a fairly easy means to inherit implementation via prototyping but this is at the expense of encapsulation.

因此,如果您的面向对象标准是多态,封装和继承的经典三人组,则Javascript不会通过。

So if your criteria for object orientation is the classic threesome of polymorphism, encapsulation and inheritance then Javascript doesn't pass.

编辑:提出补充问题原型继承如何牺牲封装?考虑这个非原型方法的例子: -

Edit: The supplementary question is raised "how does prototypal inheritance sacrifice encapsulation?" Consider this example of a non-prototypal approach:-

function MyClass() {
    var _value = 1;
    this.getValue = function() { return _value; }
}

_value属性是封装的,不能由外部代码直接修改。我们可能会在类中添加一个mutator来修改它,完全由作为类的一部分的代码控制。现在考虑对同一类的原型方法: -

The _value attribute is encapsulated, it cannot be modified directly by external code. We might add a mutator to the class to modify it in a way entirely controlled by code that is part of the class. Now consider a prototypal approach to the same class:-

function MyClass() {
  var _value = 1;
}
MyClass.prototype.getValue = function() { return _value; }

这已经破了。由于分配给getValue的函数不再在_value范围内,因此无法访问它。我们需要将_value提升为这个的属性,但这样可以在为类编写的代码控制之外进行访问,因此封装会被破坏。

Well this is broken. Since the function assigned to getValue is no longer in scope with _value it can't access it. We would need to promote _value to an attribute of this but that would make it accessable outside of the control of code written for the class, hence encapsulation is broken.

尽管如此,我的投票仍然是Javascript是面向对象的。为什么?因为给出了 OOD ,我可以在Javascript中实现它。

Despite this my vote still remains that Javascript is object oriented. Why? Because given an OOD I can implement it in Javascript.

这篇关于JavaScript是面向对象的吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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