【问题标题】:javascript class constructor initialize arrayjavascript类构造函数初始化数组
【发布时间】:2020-01-23 13:15:34
【问题描述】:

所以我想知道如何在类构造函数中初始化数组:

class test{

    constructor(){
        //here i want to initialize a new array called "array" from the class "class2"
        let array = [new class2()]; //is this the way to do it?
    }

    add(x){
        for(let i=0; i<array.length; i++){
            if(array[i] == null){
                array[i] = x;
                break;
            }
        }
    }
}

我想为该数组提供另一个类的一些值,例如 class2 有另一个带有一些值的构造函数(比如说名字和年龄)

【问题讨论】:

  • 您可以使用 class2 扩展您的类并使用 super() 函数来委托来自 class2 的值

标签: javascript arrays object constructor


【解决方案1】:

您初始化的变量将绑定到构造函数上下文。这意味着您可以在构造函数中再次使用它们,但在该函数之外无法访问它们。

由于您使用的是 ES6 类,您可以添加一个包含该数组的类变量。您需要使用 this 访问它,但它可以正常工作。

class test{


    constructor(){
        // this variable will be accessible from everywhere in the class
        this.array = [new class2()]; 
    }

    add(x){
        for(let i = 0; i < this.array.length; i++){
            if(this.array[i] == null){
                this.array[i] = x;
                break;
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2014-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-12
    • 2012-07-11
    • 1970-01-01
    • 2013-12-30
    相关资源
    最近更新 更多