在Javascript中向Array对象添加方法?

时间:2012-07-10 21:09:24

标签: javascript

是否可以在javascript中向array()添加方法? (我知道原型,但我不想为每个数组添加一个方法,特别是一个)。

我想这样做的原因是因为我有以下代码

function drawChart()
{
    //...
    return [list of important vars]
}

function updateChart(importantVars)
{
    //...
}

var importantVars = drawChart();

updateChart(importantVars);

我希望能够做到这样的事情:

var chart = drawChart();<br>
chart.redraw();

我希望有一种方法可以将方法附加到我在drawChart()返回的内容中。有办法吗?

5 个答案:

答案 0 :(得分:35)

数组是对象,因此可以包含方法:

等属性
var arr = [];
arr.methodName = function() { alert("Array method."); }

答案 1 :(得分:8)

是的,很容易做到:

array = [];
array.foo = function(){console.log("in foo")}
array.foo();  //logs in foo

答案 2 :(得分:4)

只需实例化数组,创建一个新属性,并为属性分配一个新的匿名函数。

var someArray = [];
var someArray.someMethod = function(){
    alert("Hello World!");
}

someArray.someMethod(); // should alert

答案 3 :(得分:3)

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;
}

这样做可以使您在收到方法后直接访问该方法 即。

var chart = drawChart();
chart.redraw();

答案 4 :(得分:0)

var arr = [];
arr.methodName = function () {return 30;}
alert(arr.methodName);
相关问题