JavaScript的“新”关键字是否被视为有害(第2部分)? [英] Is JavaScript 's “new” Keyword Considered Harmful (Part 2)?

查看:90
本文介绍了JavaScript的“新”关键字是否被视为有害(第2部分)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

通过以下问题阅读,我感受到了大部分答案错过了为什么有些人(Crockford)选择不使用new关键字。这不是为了防止在没有new关键字的情况下意外调用函数。

Reading through the following question, I feel the majority of the answers miss the point of why some people (Crockford) choose not to use the "new" keyword. It's not to prevent accidental calling of a function without the "new" keyword.

根据以下文章通过Crockford关于原型继承,他实现了一种对象创建技术,更清楚地展示了JS的原型性质。现在,这项技术甚至可以在 JS 1.8.5 中实现。

According to the following article by Crockford regarding prototypal inheritance, he implements an object creation technique that more clearly demonstrates the prototypal nature of JS. This technique is now even implemented in JS 1.8.5.

他反对使用new的论点可以更清楚地概括为:

His argument against using new can be more clearly summed up as:

这个间接是旨在使语言对经过专业训练的程序员来说更熟悉,但却没有做到这一点,正如我们从Java程序员对JavaScript的非常低级的看法中看到的那样.JavaScript的构造函数模式并没有吸引经典人群。它也模糊了JavaScript的真实性原型性质。因此,很少有程序员知道如何有效地使用该语言。

我不一定认为新有害的,但我同意它确实掩盖了JavaScript真正的原型性质,因此我在这一点上必须同意Crockford。

I don't necessarily consider "new" harmful, but I do agree that it does "obscure JavaScript's true prototypal nature," and therefore I do have to agree with Crockford on this point.

您对此有何看法?使用更清晰的原型对象创建离子技术,过度使用new关键字?

What is your opinion of using a "clearer" prototypal object creation technique, over using the "new" keyword?

推荐答案

你没错,使用 new 被认为是有害的,因为它没有足够强调JavaScript是原型的OO。主要问题是行为太像经典类,而一个不应该考虑 class 。人们应该考虑对象并使用现有对象创建新对象作为蓝图。

You right, using new is considered harmful as it doesn't place enough emphasis on OO in JavaScript being prototypical. The main issue is that acts too much like classical classes and one should not think about class. One should think about Object's and creating new Objects with existing objects as blueprints.

new 是JavaScript接受类似Java语法以获得受欢迎程度的日子的残余。

new is a remnant of the days where JavaScript accepted a Java like syntax for gaining "popularity".

这些天我们 Object.create 并使用 ES5垫片

不需要 new 再见。

在ES5普遍实施之前(只有FF3.6和IE8懈怠)我们使用 new someFunction.prototype 是进行原型继承的方法。

Before the days of ES5 being commonly implemented (only FF3.6 and IE8 are slacking) we used new because we had little choice. someFunction.prototype was the way to do prototypical inheritance.

我最近写了nice演示 Object.create 虽然我仍然需要解决一些问题。重要的是将对象与工厂函数分开。

I recently wrote up a "nice" demonstration of Object.create although I still need to iron out some kinks in the usage. The important thing is to separate Objects from factory functions.

这篇关于JavaScript的“新”关键字是否被视为有害(第2部分)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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