search

Home  >  Q&A  >  body text

JS problem declaring array in class

1

2

3

4

5

6

7

8

9

10

<code>var dynamic_particle=function(){

        this.init();

    }

dynamic_particle.prototype={

       init:function(){

           this.a=new Array();

           this.a.push(1);

           alert(a[0]);

        }

    }</code>

a error is undefined

淡淡烟草味淡淡烟草味2897 days ago762

reply all(2)I'll reply

  • 仅有的幸福

    仅有的幸福2017-05-19 10:27:21

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    <code>var dynamic_particle=function(){

            this.init();

        }

    dynamic_particle.prototype={

           init:function(){

               this.a=new Array();

               this.a.push(1);

               alert(this.a[0]);

            }

        }</code>

    You all know how to use this.a before. Why not add this. when using alert... an error will definitely be reported

    reply
    0
  • 習慣沉默

    習慣沉默2017-05-19 10:27:21

    Encapsulation method is generally used like this:

    1

    2

    3

    4

    5

    6

    7

    8

    9

    10

    11

    12

    13

    14

    15

    16

    17

    18

    19

    20

    21

    22

    23

    24

    <code class="javascript">var defOpt = {

        a: [1]

    }

     

    var dynamic_particle=function(options){

        if(!(this instanceof dynamic_particle)){

            return new dynamic_particle(options);

        }

        this.opt = $.extend({}, defOpt, options);

        this.init();

    }

    dynamic_particle.prototype={

     

        init:function(){

           console.log('初始化数据:', this.opt);

        },

        other: function() {

            console.log('调用option中的新数据', this.opt.newData);

        }

    }

    var dp = dynamic_particle({

        newData: [2]

    })

    dp.other()</code>

    reply
    0
  • Cancelreply