首页 > 解决方案 > 为什么使用函数来创建数据结构而不是类?它甚至正确吗?

问题描述

我比较了我在网上找到的代码和我的讲师给我的代码。我很困惑为什么我的讲师使用函数来创建数据结构而不是像我在网上找到的那样创建数据结构。哪一个更好?班级?功能?

这是我的讲师创建堆栈的代码

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);
    };
}

只是几个问题

  1. 为什么使用函数而不是类?

  2. 为什么使用var Stack = function(){堆栈和function Queue(){队列?有什么不同吗?

  3. 为什么使用this.push = function(value){?我认为它应该像function push(){

标签: javascriptdata-structures

解决方案


首先,两种使用方式没有区别,它们的工作方式相同。也是this.push = function(value){ ... }您在 Javascript 中定义方法的方式


推荐阅读