簡體   English   中英

如何在 class 中調用 function?

[英]How to call a function inside a class?

因此,如果您想調用它,我正在嘗試學習基於 class 或 OOP 並且我正在編寫鏈接列表。 所以我創建了一個 class 並編寫了某些功能。 我很難弄清楚如何調用這些函數,以便我可以console.log記錄 output。 In Javascript i can simply call the some function by console.log(functionName) and see the output but how do i do it with class based functions?

我只想在linkedList class 中調用所有這些函數,例如sizeinsertFirst等,然后控制台記錄輸出。 我怎樣才能達到同樣的效果?

我是 OOP 世界的新手,所以請原諒任何無知,或者如果您覺得這是一個愚蠢的問題。

檢查此代碼:-

 class Node {
    constructor(data, next = null) {
        this.data = data;
        this.next = next;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
    }

  insertFirst(data) {
      this.head = new Node(data, this.head);
  }  

  size() {
      let counter = 0;
      let node = this.head;

      while(node) {
          counter++
          node = node.next
      }
      return counter;
  }
}

const list = console.log(new LinkedList());
list.head = console.log(new Node(10));

感謝所有幫助! 謝謝

-- 編輯:我稍微修改了你的課程。 我認為我在LinkedList class 中編寫的print方法可能對您有幫助,我更setHead方法而insertFirst --

class Node {
    constructor(data, next = null) {
        this.data = data;
        this.next = next;
    }
}

class LinkedList {
    constructor() {
        this.head = null;
    }

  setHead(node) {
      this.head = node;
  }  

  size() {
      let counter = 0;
      let node = this.head;

      while(node) {
          counter++
          node = node.next
      }
      return counter;
  }

  print() {
      let node = this.head;
      while(node) {
          console.log(node.data);
          node = node.next
      }
  }
}

let myList = new LinkedList();
let bob = new Node("bob");
let joe = new Node("joe", bob);
let carl = new Node("carl", joe)
let alice = new Node("alice", carl)
myList.setHead(alice);

// print the data in the nodes
console.log(carl.data);
console.log(bob.data);
console.log(joe.data);
console.log(alice.data);

// print size
console.log(myList.size())

// print the entire list
myList.print()

console.log()分配給變量總是會導致 undefined 你可能想試試這個

const lists =new LinkedList()
console.log(lists)
lists.head = new Node(10)
console.log(lists.head)

to call a function inside a class you first create an object from the class using the constructor and pass any values to the contractor and then you simply call the function like this

 class classobject{ constructor (apple){ this.apple=apple } printName(){ console.log(this.apple,"apple")} } const apple= new classobject("granny ") apple.printName()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM