javascript - 为什么使用函数来创建数据结构而不是类?它甚至正确吗?
问题描述
我比较了我在网上找到的代码和我的讲师给我的代码。我很困惑为什么我的讲师使用函数来创建数据结构而不是像我在网上找到的那样创建数据结构。哪一个更好?班级?功能?
这是我的讲师创建堆栈的代码
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(){
解决方案
首先,两种使用方式没有区别,它们的工作方式相同。也是this.push = function(value){ ... }
您在 Javascript 中定义方法的方式
推荐阅读
- python - python正则表达式:如何忽略不相关的匹配?
- linux - 如何在不运行容器的情况下向容器发送命令以更改文件?
- azure - 确保 Authorization 标头的值正确形成,包括签名
- c - 结构数组有问题解决C中的问题
- google-cloud-platform - 无法通过 SSH 连接到 GCP 计算引擎
- python - 为什么 get() 方法不返回任何值?
- wordpress - 在自定义、循环外、页面上设置语言
- javascript - 如何从 Go Web 程序集“抛出”JS 错误?
- openshift - 4.7 版中 OpenShift SDN 的默认 CIDR 是多少?
- python - 计数交换和比较 insertSort