0

I want to create a method in javascript which can be used by every object which is an element. no need to add the method like

object = {
 methodName : function(){

 }
};
  • 3
    Extend `Object` prototype, maybe? – Adam Azad Jun 19 '17 at 12:42
  • 2
    Possible duplicate of [javascript add prototype method to all functions?](https://stackoverflow.com/questions/2126844/javascript-add-prototype-method-to-all-functions) – krillgar Jun 19 '17 at 12:44
  • 1
    Also see [Why is extending native objects a bad practice?](https://stackoverflow.com/questions/14034180/why-is-extending-native-objects-a-bad-practice) – Alex K. Jun 19 '17 at 12:46

1 Answers1

0

Your best bet is to extend Object prototype.

// extend
Object.prototype.myFunction = function(){
   console.log('universal Object function');
}
// now every object created and instance of Object will have the method myFunction available to use.
var a = {};
a.myFunction();

Please, bear in mind this Why is extending native objects a bad practice?

Adam Azad
  • 11,171
  • 5
  • 29
  • 70
  • If you're going to extend `Object.property` you should at least do it with `Object.defineProperty()` and make sure the new property is not enumerable. – Lennholm Jun 19 '17 at 12:53