【问题标题】:How to call a function inside a class?如何在类中调用函数?
【发布时间】:2020-10-19 04:33:38
【问题描述】:

因此,如果您想调用它,我正在尝试学习基于类或 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));

感谢所有帮助!谢谢

【问题讨论】:

  • console.log 包装您的构造函数调用会记录该对象,然后将其丢弃并将console.log 的返回值(即undefined)分配给您的const listlist.head 变量。只需执行const list = new LinkedList() 并稍后在另一行使用console.log(list) 记录它,如果您愿意。 console.log 显示输出,与您似乎指出的帮助调用方法无关。
  • @ggorlen 哦,我明白了!我认为这是有道理的!顺便说一句,谢谢你的提示!!我现在终于可以在控制台中看到我的输出了!!如果您将此添加为答案,我会接受。

标签: javascript oop linked-list


【解决方案1】:

-- 编辑:我稍微修改了你的课程。我认为我在LinkedList 类中编写的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()

【讨论】:

  • 嘿谢谢!!这行得通,这很棒,因为它开始对我有意义了!!
【解决方案2】:

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()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    • 1970-01-01
    相关资源
    最近更新 更多