1

Good day to everybody,

is there a method to augment the javascript Object and Function elements avoinding conflict issues? Let me be more specific:

Suppose i have 2 .js files :

ex1.js has Object.prototype.aMethod=function(){/*a function*/}

ex2.js has Object.prototype.aMethod=function(){/*another function*/}

In this situation, the ex1.js augmentation is overwritten by the one on ex2.js .

My question :

Is there a way to limit the effects of an augmentation to his file context, or better, to a module context?

EDIT:

Actually, i am reading crockford' s book JavaScript: the good parts, where he uses the prototype augmentation of Object and Function as something normal to do, without talking about the conflict issue. that' s strange, since the book leans to not pollute the global namespace. So i thought there must be some sort of workaround.

3
  • 3
    You shouldn't be mutating the global Object.prototype. Commented Feb 3, 2013 at 13:11
  • David is right. How about you explain what you are trying to do with this, and we can suggest how you should be doing it differently. Commented Feb 3, 2013 at 13:13
  • I think Crockford gets around to explaining why mutating Object is wrong. You should use aMethod(thisObj, args...) instead of thisObj.aMethod(args...) at the very least. Commented Feb 3, 2013 at 13:46

1 Answer 1

2

The prototype modifications are global if the Object you're modifying is global. To support what you're trying to do, you could use a module-local prototype:

var MyObject = function(properties) {
  var key;
  for(key in properties) {
    if(properties.hasOwnProperty(key)) {
      this[key] = properties[key];
    }
  }
};

MyObject.prototype.aMethod = function() {
  console.log(this.name);
}

var obj = new MyObject({name: "blah"});
obj.aMethod();

// Prints "blah"

Modifying Object.prototype is usually considered "evil" on javascript, since the inherited properties show up on every for-in loop afterwards. Please note that modifying Object.prototype is different from modifying the Object object, which is what libraries such as Sugar.JS usually do.

Sign up to request clarification or add additional context in comments.

2 Comments

I see. that seems a little troubling in respect to what' s worth. native augmentation is something i should use when i am sure i am working in a controlled environment . thank you for the response
The problem usually lies on Object.prototype, because of the for..in loop. Modifying Array.prototype, String.prototype and others usually isn't as troublesome. It is important to note that some libraries, such as jQuery, assume that you don't modify Object.prototype.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.