javascript 向所有函数添加原型方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2126844/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
javascript add prototype method to all functions?
提问by salmane
Is there a way to add a method to all javascript functions without using the prototype library?
有没有办法在不使用原型库的情况下向所有 javascript 函数添加方法?
something along the lines of :
类似的东西:
Function.prototype.methodName = function(){
return dowhateverto(this)
};
this is what i tried so far but it didnt work. Perhaps it is a bad idea also if so could you please tell me why?
这是我到目前为止尝试过的,但没有奏效。也许这也是一个坏主意,如果是的话,你能告诉我为什么吗?
if so can I add it to a set of functions i choose
如果可以,我可以将它添加到我选择的一组函数中吗
something like :
就像是 :
MyFunctions.prototype.methodName = function(){
return dowhateverto(this)
};
where MyFunctions is an array of function names
其中 MyFunctions 是一个函数名称数组
thank you
谢谢你
回答by troelskn
Sure. Functions are objects:
当然。函数是对象:
var foo = function() {};
Function.prototype.bar = function() {
alert("bar");
};
foo.bar();
Will alert "bar"
会提醒“酒吧”
回答by thomasrutter
Try Object.prototype instead:
试试 Object.prototype:
Object.prototype.methodName = function(){
return dowhateverto(this)
};
But also heed the warning that extending native objects is not always a good idea.
但也要注意扩展本机对象并不总是一个好主意的警告。
Function.prototype can't really be manipulated reliably in Javascript; it isn't a real object, because Function() constructor needs to return a function, not an object. But, you can't treat it like a normal function either. Its behaviour when you try to access its 'properties' may be undefined and vary between browsers. See also this question.
Function.prototype 在 Javascript 中无法真正可靠地操作;它不是一个真正的对象,因为 Function() 构造函数需要返回一个函数,而不是一个对象。但是,您也不能将其视为正常功能。当您尝试访问其“属性”时,其行为可能未定义且因浏览器而异。另请参阅此问题。
回答by Luca Matteis
function one(){
alert(1);
}
function two(){
alert(2);
}
var myFunctionNames = ["one", "two"];
for(var i=0; i<myFunctionNames.length; i++) {
// reference the window object,
// since the functions 'one' and 'two are in global scope
Function.prototype[myFunctionNames[i]] = window[myFunctionNames[i]];
}
function foo(){}
foo.two(); // will alert 2
回答by Mic
Changing JS built-in objects can give you some surprises.
If you add external libraries or changing the version of one of them, you are never sure that they won't overwrite your extension.
改变JS内置对象可以给你一些惊喜。
如果您添加外部库或更改其中之一的版本,您永远无法确定它们不会覆盖您的扩展。

