N
N
neoneel2018-02-11 18:56:40
JavaScript
neoneel, 2018-02-11 18:56:40

How to access class constructor arguments?

class NameClass{
  constructor(){
    //
                //
  }
method1(){
//
//
}
}

how to pass constructor arguments to method1?
or how to implement adding objects to a linked list when creating a new list?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Anton Spirin, 2018-02-11
@neoneel

You cannot access constructor arguments from class methods, but you can make them class fields in the constructor:

class Counter {
  constructor(value) {
    this.value = value || 0;  // определяем поле класса value со значением аргумента value
  }                           // либо 0 если аргумент не будет передан
  
  getVaue() {
    return this.value;
  }

  increment() {
    return ++this.value;
  }

  decrement() {
    return --this.value;
  }
}

I recommend trying to write a linked list on your own. If you do not want to do it yourself, then look under the spoiler.
spoiler
class Node {
  constructor(data) {
    this.data = data;
    this.next = null;
  }
}

class LinkedList {
  constructor() {
    this.head = null;
    this.length = 0;
    
    Array.prototype.forEach.call(arguments, data => this.add(data));
  }

  add(data) {
    const nodeToAdd = new Node(data);
    let nodeToCheck = this.head;

    if(!nodeToCheck) {
      this.head = nodeToAdd;
      this.length++;
      return nodeToAdd;
    }

    while(nodeToCheck.next) {
      nodeToCheck = nodeToCheck.next;
    }
    
    nodeToCheck.next = nodeToAdd;
    this.length++;

    return nodeToAdd;
  }

  get(num) {
    const nodeToCheck = this.head;
    let count = 0;
  
    if(num > this.length) {
      return "Doesn't Exist!"
    }

    while(count < num) {
      nodeToCheck = nodeToCheck.next;
      count++;
    }

    return nodeToCheck;
  }

  remove(num) {
    let nodeToCheck = this.head;
    let length = this.length;
    let count = 0;
    let prevNode = null;
     
     if(num > length) {
       return "Doesn't Exist!"
     }
   
     if(num === 0) {
       this.head = nodeToCheck.next;
       this.length--;
       return this.head;
     }
     
     while(count < num) {
       prevNode = nodeToCheck;
       nodeToCheck = nodeToCheck.next;
       count++;
     }
     
     prevNode.next = nodeToCheck.next;
     nodeToCheck = null;
     this.length--;
      
     return this.head;
  }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question