简体   繁体   中英

Add Prototype Method on all Variables

Is it possible to add a Method to all Javascript Prototypes ( Object,array,function,string,number,boolean )?

Just for Example. If i would like to add a new Prototype getter, which returns the Type of the Variable, the create Timestamp or something else, how could I do that?

For Information: It's not about what this function does!

Edit:

I would like to access the Function like every other Prototypen Function:

myVariable.myMethod(myParam)

Every JavaScript variable is either an object, or it auto-boxes to an object (like string, boolean and number), or it is null or undefined explicitly.

So, it seems like if you want to add a method to all those, you can add a function to Object.prototype which they all extend like Bar suggested.

Object.prototype.myMagic = function(){
    console.log("Hello");
};
"thisString".myMagic();
15.13.myMagic();
([]).myMagic();

Note that you are in fact not adding a function to the prototype of a string since a string is a primitive value and doesn't have a prototype, rather, you're adding a method to the prototype of Object - and strings "box" to String instances (which are objects) that extend Object and will have this method.

Also note that on ES5 systems, it's possible to create objects that do not extend Object.prototype via Object.create(null) , in ES6 it's also possible to modify the prototype of objects via setPrototypeOf or __proto__ . However, outside those edge cases it should work.

You can add it to Object.prototype . All other prototype instances extend Object.prototype , and will inherit it from there.

Object.prototype.myMethod=function() {
   // ... whatever
};

Please note that extending built-in prototypes is not a recommended practice for "real-world" code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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