简体   繁体   English

动态创建原型并推送到数组

[英]dynamically create prototypes and push to array

I'm trying to dynamically create objects of 'test' that are pushed to an array, I know the code below doesn't work, it's for reference to help solve my problem: 我正在尝试动态创建被推送到数组的“测试”对象,我知道下面的代码不起作用,仅供参考以帮助解决我的问题:

var test = (function(){
    var blah;

    test.prototype.getNumber=function(){
        return blah;
    }
    test.prototype.setNumber=function(val){
        blah=val;
    }
});

var array=(function(){
    var array[];

    array.prototype.get=function(index){
        return array[index];
    }
    array.prototype.set=function(obj){
        array.push(obj);
    }

});

var objArray=new array();

for(var i=0;i<6;i++){
    objArray.set({
        setNumber(5);
    }=new test());
}

The first step would be to create your constructor functions properly. 第一步是正确创建构造函数。 It seems you want to simulate private properties by using local variables and closures. 似乎您想通过使用局部变量和闭包来模拟私有属性。 In that case you have to assign the methods to the instance itself, not the prototype: 在这种情况下,您必须将方法分配给实例本身,而不是原型:

this.setNumber = function(){
    return blah;
};
// instead of
// test.prototype.setNumber = ...;

The same for array . array

To add an instance, all you have to do is create a new test instance and call its setNumber method: 要添加实例,您要做的就是创建一个新的test实例并调用其setNumber方法:

for(var i=0;i<6;i++){
    var obj = new test();
    obj.setNumber(5);
    objArray.set(obj);
}

Note: Constructor function names usually start with a capital letter. 注意:构造函数的名称通常以大写字母开头。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM