0

i can't figure it out on how to get the values of a static method of a class. my code is below.

class Field {
    constructor(rows = 11, cols = 10) {
    this.numRows = rows
    this.numCols = cols
    }

    static loadFromFileContents(contents) {
        this.numCols = contents.split('x')[0]
        this.numRows = contents.split('x')[1]

    }
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)

first of all, i want to get the instance of the static method. something like this instanceof(field), it should be equal to 'Field'. but i don't know if my syntax is correct for getting the instance. Second i want the return value of field.numCols should be equal to 4 because of the first split value and field.numRows should be equal to 5. sorry i'm not that familiar with static method of a class. i hope you can help me with my problem. thank you so much.

1
  • yes, mybad i did not notice it. i already fix it Commented Mar 17, 2020 at 4:27

1 Answer 1

2

It sounds like the static method needs to parse the passed string and return a new Field instance:

class Field {
  constructor(rows = 11, cols = 10) {
    this.numRows = rows
    this.numCols = cols
  }

  static loadFromFileContents(contents) {
    const [rows, cols] = contents.split(' x ');
    return new Field(rows, cols);
  }
}
const contents = `4 x 5`
const field = Field.loadFromFileContents(contents)
console.log(field.numCols)
console.log(field.numRows)

Sign up to request clarification or add additional context in comments.

2 Comments

wow thanks. it worked. how about this assert.instanceOf(field, Field)? how can i make the instance of the field equal to Field?
You can use field instanceof Field, which shows that it resolves to true

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.