Add a method to Array object in Javascript?

前端 未结 5 1915
梦如初夏
梦如初夏 2020-12-09 17:40

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

5条回答
  •  生来不讨喜
    2020-12-09 18:04

    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.

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

提交回复
热议问题