如何在类内部调用函数?

时间:2020-06-29 03:48:03

标签: javascript oop linked-list

所以我想学习基于类或OOP的方法,如果您想调用它,我正在编写一个链接列表。因此,我创建了一个类并编写了某些功能。我很难弄清楚如何调用这些函数,以便可以console.log输出。在Javascript中,我可以简单地通过console.log(functionName)调用some函数并查看输出,但是如何使用基于类的函数呢?

我只想在linkedList类内调用所有这些函数,例如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));

感谢所有帮助!!谢谢

2 个答案:

答案 0 :(得分:1)

-编辑:我对您的班级做了一些修改。我认为我在print类中编写的LinkedList方法可能对您有所帮助,并且我更喜欢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()

答案 1 :(得分:1)

console.log()分配给变量将始终导致未定义 您可能想尝试一下

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

要在类内调用函数,首先要使用构造函数从该类创建一个对象,并将所有值传递给承包商 然后只需调用这样的函数

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