在Javascript中向Array对象添加方法? [英] Add a method to Array object in Javascript?

查看:192
本文介绍了在Javascript中向Array对象添加方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

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

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();

我希望有一种方法可以将方法附加到我返回的 drawChart()。有什么方法吗?

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?

推荐答案

数组是对象,因此可以保存方法等属性:

Arrays are objects, and can therefore hold properties such as methods:

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

这篇关于在Javascript中向Array对象添加方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆