所以我想学习基于类或OOP的方法,如果您想调用它,我正在编写一个链接列表。因此,我创建了一个类并编写了某些功能。我很难弄清楚如何调用这些函数,以便可以console.log
输出。在Javascript中,我可以简单地通过console.log(functionName)
调用some函数并查看输出,但是如何使用基于类的函数呢?
我只想在linkedList类内调用所有这些函数,例如size
,insertFirst
等,并控制台记录输出。我怎么能达到同样的目的?
我是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));
感谢所有帮助!!谢谢
答案 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()