1

so i wonder how to initialize an array in a class constructor:

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;
            }
        }
    }
}

i want to make give that array some values of another class, like class2 has another constructor with some values (lets say name and age)

1
  • you can extend your class with class2 and use super() function to delegate values from class2 Commented Jan 23, 2020 at 13:17

1 Answer 1

1

The variable your initialize will be bound to the constructor context. Which mean you could use them again in the constructor but it won't be accessible outside of that function.

Since you are using ES6 classes, you could add a class variable that would contains this array. You would need to access it using this but it would work fine.

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;
            }
        }
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.