【发布时间】:2020-08-10 02:50:24
【问题描述】:
我比较了我在网上找到的代码和我的讲师给我的代码。我很困惑为什么我的讲师使用函数来创建数据结构而不是像我在网上找到的那样创建数据结构。哪一个更好?班级?功能?
这是我的讲师创建堆栈的代码
var Stack = function(){
//Class members
this.count = 0;
this.storage = {};
//Add item
this.push = function(value){
this.storage[this.count] = value;
this.count++;
}
//Delete item
this.pop = function(){
if(this.count === 0){
return undefined;
}
this.count--;
var result = this.storage[this.count];
delete this.storage[this.count];
return result;
}
//Return the sie of the stack
this.size = function(){
return this.count;
}
//View the top of the stack
this.top = function(){
return this.storage[this.count-1];
}
}
这是我的讲师创建链表的代码
function Queue(){
this.collection = [];
//Print the collection
this.print = function(){
document.write(this.collection + "<br/>");
};
//Add item in queue
this.addQ = function(element){
this.collection.push(element);
};
//Remove item at the front
this.deQ = function(){
return this.collection.shift(); //Left shift
};
//Return first item
this.front = function(){
return this.collection[0];
};
//Return the size of queue
this.size = function(){
return this.collection.length;
};
//Check the queue status: Empty or not
this.isEmpty = function(){
return (this.collection.length === 0);
};
}
几个问题
为什么使用函数而不是类?
为什么将
var Stack = function(){用于堆栈而function Queue(){用于队列?有什么不同吗?为什么要使用
this.push = function(value){?我认为它应该像function push(){
【问题讨论】:
-
嘿,你知道吗,在真正的 javascript 中,你可能永远不会编写自己的堆栈或队列类,因为内置数组已经像堆栈和队列一样起作用。您的讲师只是将它们用作示例。
标签: javascript data-structures