原型在JavaScript中是不是很糟糕? [英] Are prototypes bad in JavaScript?

查看:100
本文介绍了原型在JavaScript中是不是很糟糕?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Felix的Node.js风格指南 中,它说:

In Felix's Node.js Style Guide it says:


不要扩展任何
对象的原型,尤其是原生对象。如果你不遵守这条规则,那么
是地狱中的一个特殊地方等你

Do not extend the prototypes of any objects, especially native ones. There is a special place in hell waiting for you if you don't obey this rule.

这篇文章也让我质疑原型的用途。如果您稍后要在代码中添加方法,为什么不将它添加到原始构造函数中呢?

This article also made me question the uses of prototypes. If you are going to add a method later on in the code, why not just add it in the original constructor?

那么,何时需要扩展原型一个对象?

So, when is it ever necessary to extend the prototype of an object?

推荐答案

不,原型并不坏。恰恰相反,JavaScript是一种原型语言,原型是假设扩展对象的方式。

No, prototypes are not bad. Quite the opposite, JavaScript is a prototypal language and prototypes are how you are supposed to extend objects.

报价反对扩展 Object.prototype 具体来说。不是对象的原型。 JavaScript中的 Everything 继承自 Object ,所以搞乱其原型会影响一切。它打破 for(var n in obj){循环并且只是烦人。

The quote is against extending Object.prototype specifically. Not "An object's prototype". Everything in JavaScript inherits from Object, so messing with its prototype effects everything. It breaks for(var n in obj){ loops and is just annoying.

这是唯一反对原型的东西 - 它们出现在for-in循环中。除此之外,它们是BY FAR,是在JS中扩展对象的最佳方式。

That's the only thing against prototypes -- they show up in for-in loops. Other than that, they are, BY FAR, the best performing way to extend objects in JS.

至于为什么 - 在构造函数中添加对象,比如说:

As for why -- Adding objects in the constructor, say:

function myClass(){
    this.someMethod = function(){ ... }
}

表示您将为该班级的每个实例提供单独的功能。通过原型来实现:

means you will have a seperate function for every instance of the class. Doing it via a prototype:

myClass.prototype.someMethod = function(){ ... }

表示只有该功能的一个副本。更高效的内存,并允许热门编辑语言。假设您要编辑String.prototype,例如:

means there will only ever be one copy of that function. Much more memory efficient, and allows for hot-editing of the language. Let's say you want to edit String.prototype, for instance:

String.prototype.trim = function(){ ... }

如果您只是以某种方式将其添加到构造函数中,现有字符串将不具有 .trim()方法,所以代码: navigator.userAgent.trim()导航器起不起作用.userAgent 是在你添加 trim()方法之前定义的。

If you just added that to the constructor somehow, existing strings would not have the .trim() method, so the code: navigator.userAgent.trim() would not work since navigator.userAgent was defined before you added your trim() method.

那个文章只是蒂姆肛门和偏执狂。忽略它:)只要你不忘记输入 new myClass()而不只是 myClass() ,你不会有任何问题。

And that article is just Tim being anal and paranoid. Ignore it :) As long as you don't forget to type new myClass() instead of just myClass(), you won't have any issues.

这篇关于原型在JavaScript中是不是很糟糕?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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