0

I've done a lot of reading about using objects in js and this is one of the techniques that I found for creating an array of objects and defining a method within each:

function myObj(){
        this.dCount = 0;

        this.myMethod = function(){
            dCount = 1;
            console.log(dCount);
        }
}

var objects = new Array();

function loadObjs(){

        for(var i = 0; i < 4; i++){
            var myObj = new Object();
            objects[i] = myObj;
        }

        objects[0].myMethod();
}

However, this (and all the other techiques I've tried) returns objects[0].myMethod is not a function.

I still don't get it. Can someone please help?

4

3 回答 3

2

您正在实例化一个通用对象,而不是您自己的。

尝试这个:

objects[i] = new myObj;
于 2012-12-25T01:36:11.970 回答
1

你还没有实例化!

代替:

var myObj = new Object();
objects[i] = myObj;

和:

objects[i] = new myObj;
于 2012-12-25T01:36:31.817 回答
1

myObj因为您将变量实例化为Object类而不是myObj类。

function myObj(){
        this.dCount = 0;

        this.myMethod = function(){
            dCount = 1;
            console.log(dCount);
        }
}

var objects = new Array();

function loadObjs(){

        for(var i = 0; i < 4; i++){
            // var myObj = new myObj();
            // objects[i] = myObj;
            // this is better to separate the variable name from class name. so:
            var m = new myObj();
            objects[i] = m;
        }

        objects[0].myMethod();
}
于 2012-12-25T01:38:06.933 回答