【问题标题】:Why use function to create a data structure instead of class? Is it even correct?为什么使用函数来创建数据结构而不是类?它甚至正确吗?
【发布时间】: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);
    };
}

几个问题

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

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

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

【问题讨论】:

  • 嘿,你知道吗,在真正的 javascript 中,你可能永远不会编写自己的堆栈或队列类,因为内置数组已经像堆栈和队列一样起作用。您的讲师只是将它们用作示例。

标签: javascript data-structures


【解决方案1】:

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

【讨论】:

    【解决方案2】:

    Javascript 是一种基于原型的语言,因此它没有真正的类。但是,ES6 添加了class 关键字,这样更易​​于阅读,但在底层仍然使用原型。

    javascript 中的一切都是对象,包括函数。当您使用new 关键字调用函数时,它会创建一个新对象并将其附加到该函数内的this。因此,在您的构造函数中,您可以执行 this.foo = function(){ 将函数附加到新对象。但是,这是低效的,因为它会在您每次创建新对象时运行。更好的方法是使用原型,这样每个函数只创建一次:

    var Stack = function() {
        // Initialize local variables.
        this.count = 0;
        this.storage = {};
    }
    
    // Attach class methods
    Stack.prototype.foo = function() { ... }
    Stack.prototype.bar = function() { ... }
    
    // Create instance of class.
    var myStack = new Stack();
    

    由于最近添加了 class 关键字,如果您想支持 IE11 或其他较旧的浏览器,则需要使用函数式方式,除非您使用的是转译器。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-03-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-27
      相关资源
      最近更新 更多