简体   繁体   English

如果我们在任何对象的Node.js中扩展原型会有什么问题?

[英]What's wrong if we extend prototypes in Node.js of any object?

Consider the following code: 请考虑以下代码:

var AryUser = new Array();
AryUser.prototype.HasUser = function() {
  if(this.length > 0)
    return true;
  else
    return false;
}

I am already using prototype extending on some objects in my Node.js Projects. 我已经在我的Node.js项目中的某些对象上使用了原型扩展。 I came across an article , which states it's bad practice. 我看到一篇文章 ,说这是不好的做法。 Does it create overhead on server during execution of such functions? 在执行此类功能时是否会在服务器上产生开销?

Can anyone tell me what the reason is? 谁能告诉我原因是什么? (Any official document referral would be of great help) (任何官方文件转介都会有很大帮助)

You are not extending any prototype in the example you provided above. 您没有在上面提供的示例中扩展任何原型。 The prototype property only exists on functions - AryUser is an array. prototype属性仅存在于函数上AryUser是一个数组。 The above code will throw a ReferenceError . 上面的代码将抛出一个ReferenceError

You may wish to learn how prototypal inheritance works in JavaScript. 您可能希望了解原型继承在JavaScript中的工作原理。 Read the following answer: https://stackoverflow.com/a/8096017/783743 阅读以下答案: https//stackoverflow.com/a/8096017/783743

That being said it's a bad practice to extend prototypes of native functions like Function , Object and Array . 据说,扩展FunctionObjectArray原生函数的原型是一种不好的做法。 This is because you might overwrite someone else's function, possibly breaking their code. 这是因为你可能会覆盖别人的功能,可能会破坏他们的代码。

Extending native function prototypes is only recommended for monkey patching . 扩展本机函数原型仅建议用于猴子修补 Read the following article to understand the pros and cons of extending native function prototypes . 阅读以下文章,了解扩展本机函数原型的优缺点

I know, I am late. 我知道,我迟到了。 I have something to share. 我有分享的东西。 Here is one way to achieve what you are trying to do. 这是实现您想要做的事情的一种方法。

function UserArray() {
  Array.call(this);
}

UserArray.prototype = Object.create(Array.prototype);
UserArray.prototype.constructor = UserArray;
UserArray.prototype.hasUser = function() {
    return this.length > 0;
};

var userArray = new UserArray();

userArray.hasUser();//false;
userArray.push({name: 'foo'});
userArray.hasUser();//true;
userArray instanceof UserArray;//true
userArray instanceof Array;//true
typeof Array.prototype.hasUser === 'undefined'//true

Maybe these articles provide some insight: 也许这些文章提供了一些见解:

Bottom line is: Extending prototypes of objects you don't own is it's not future-proof if browsers change, and you get problems with libraries from others doing the same. 底线是:扩展您不拥有的对象的原型,如果浏览器发生变化,它将不会出现面向未来的问题,并且您会遇到其他人做同样的库的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM