簡體   English   中英

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

[英]Add a method to Array object in 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()返回的drawChart() 有辦法嗎?

數組是對象,因此可以包含諸如方法之類的屬性:

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

是的,容易做到:

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

只需實例化數組,創建一個新屬性,並為該屬性分配一個新的匿名函數。

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

someArray.someMethod(); // should alert
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();
var arr = [];
arr.methodName = function () {return 30;}
alert(arr.methodName);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM