在 Javascript 中向 Array 对象添加方法?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11421986/
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
Add a method to Array object in Javascript?
提问by user1167650
Is it possible to add a method to an array() in javascript? (I know about prototypes, but I don't want to add a method to every array, just one in particular).
是否可以在javascript中向array()添加方法?(我知道原型,但我不想为每个数组添加一个方法,特别是一个)。
The reason I want to do this is because I have the following code
我想这样做的原因是因为我有以下代码
function drawChart()
{
//...
return [list of important vars]
}
function updateChart(importantVars)
{
//...
}
var importantVars = drawChart();
updateChart(importantVars);
And I want to be able to do something like this instead:
我希望能够做这样的事情:
var chart = drawChart();<br>
chart.redraw();
I was hoping there was a way I could just attach a method to what i'm returning in drawChart()
. Any way to do that?
我希望有一种方法可以将方法附加到我要返回的内容上drawChart()
。有没有办法做到这一点?
回答by jeff
Arrays are objects, and can therefore hold properties such as methods:
数组是对象,因此可以保存诸如方法之类的属性:
var arr = [];
arr.methodName = function() { alert("Array method."); }
回答by jjathman
Yep, easy to do:
是的,很容易做到:
array = [];
array.foo = function(){console.log("in foo")}
array.foo(); //logs in foo
回答by Justin Niessner
Just instantiate the array, create a new property, and assign a new anonymous function to the property.
只需实例化数组,创建一个新属性,并为该属性分配一个新的匿名函数。
var someArray = [];
var someArray.someMethod = function(){
alert("Hello World!");
}
someArray.someMethod(); // should alert
回答by Aust
function drawChart(){
{
//...
var importantVars = [list of important variables];
importantVars.redraw = function(){
//Put code from updateChart function here using "this"
//in place of importantVars
}
return importantVars;
}
Doing it like this makes it so you can access the method directly after you receive it.
i.e.
这样做可以使您在收到该方法后可以直接访问该方法。
IE
var chart = drawChart();
chart.redraw();
回答by sandeep kumar
var arr = [];
arr.methodName = function () {return 30;}
alert(arr.methodName);