0

I have this simple code:

var num = [12,13]
class Test {
  constructor(num){
    this.num = num
  }

  change() {
  this.num[1] = 5
  }

}

test = new Test(5)
test.change()
alert(test.num[0] + ' x ' + num)

I am trying to change the value of this.num through the change method. However, I get the following error:

Uncaught TypeError: Cannot create property '1' on number '5'

Can someone please explain what I am doing wrong here? Here's a fiddle, if it helps. Thank you

4
  • 2
    As the error is trying to tell you, a number is not an array. Commented Mar 17, 2019 at 16:17
  • 3
    you pass 5 to the constructor of Test, a number is not iterable Commented Mar 17, 2019 at 16:17
  • 2
    It should probably be test = new Test(num) Commented Mar 17, 2019 at 16:18
  • yes. :))) thank you. my bad <3 Commented Mar 17, 2019 at 16:19

1 Answer 1

1

You are passing num = 5 to constructor. And this.num will be 5. num inside constructor is not refering to the num in global scope. Instead it creates a private variable num which is passed as 5

You should pass num to contructor()

var num = [12,13]
class Test {
  constructor(num){
    this.num = num
  }

  change() {
    this.num[1] = 5
  }

}

test = new Test(num)
test.change()
alert(test.num[0] + ' x ' + num)

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.