Amol M Kulkarni
Amol M Kulkarni

Reputation: 21639

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. 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)

Upvotes: 1

Views: 2793

Answers (3)

user405398
user405398

Reputation:

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

Upvotes: 1

crackmigg
crackmigg

Reputation: 5901

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.

Upvotes: -1

Aadit M Shah
Aadit M Shah

Reputation: 74234

You are not extending any prototype in the example you provided above. The prototype property only exists on functions - AryUser is an array. The above code will throw a ReferenceError.

You may wish to learn how prototypal inheritance works in JavaScript. Read the following answer: 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. 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.

Upvotes: 3

Related Questions