简体   繁体   English

在所有变量上添加原型方法

[英]Add Prototype Method on all Variables

Is it possible to add a Method to all Javascript Prototypes ( Object,array,function,string,number,boolean )? 是否可以将方法添加到所有Javascript原型( 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? 如果我想添加一个新的Prototype getter,它返回变量的类型,创建时间戳或其他内容,我该怎么做?

For Information: It's not about what this function does! 参考信息:与该功能的作用无关!

Edit: 编辑:

I would like to access the Function like every other Prototypen Function: 我想像其他所有Prototypen函数一样访问函数:

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. 每个JavaScript变量要么是一个对象,要么自动装箱到一个对象(如字符串,布尔值和数字),或者为null或未明确定义。

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添加一个函数,它们都像Bar建议的那样进行扩展。

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. 请注意,实际上您并未在字符串的原型中添加函数,因为字符串是原始值并且没有原型,而是在Object的原型中添加了一个方法-字符串“ box”到扩展Object并具有此方法的String实例(它们对象)。

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__ . 还要注意,在ES5系统上,可以通过Object.create(null)创建扩展Object.prototype对象,在ES6中,也可以通过setPrototypeOf__proto__修改对象的原型。 However, outside those edge cases it should work. 但是,在这些极端情况之外,它应该可以工作。

You can add it to Object.prototype . 您可以将其添加到Object.prototype All other prototype instances extend Object.prototype , and will inherit it from there. 所有其他原型实例都扩展Object.prototype ,并将从那里继承它。

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

Please note that extending built-in prototypes is not a recommended practice for "real-world" code. 请注意,对于“实际”代码,不建议扩展内置原型。

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

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