zoukankan      html  css  js  c++  java
  • [Javascript] Constructor Functions and prototype

    Let's see two code snippets which has same functionalities:

    No1:

    function Cart(items = []) {
      this.items = Object.freeze(items);
      this.add = item => {
        const state = [...this.items, item];
        this.items = Object.freeze(state);
      };
      this.remove = id => {
        const state = this.items.filter(item => item.id !== id);
        this.items = Object.freeze(state);
      };
    }
    const cart = new Cart();
    console.log(cart);

    No2:

    function Cart(items = []) {
      this.items = Object.freeze(items);
    }
    
    Cart.prototype.add = function(item) {
      const state = [...this.items, item];
      this.items = Object.freeze(state);
    };
    Cart.prototype.remove = function(id) {
      const state = this.items.filter(item => item.id !== id);
      this.items = Object.freeze(state);
    };
    
    const cart2 = new Cart();
    console.log(cart2);

    Which one is better?

    Well No2 is better, but why?

    We console log the 'cart' & 'cart2', see what do they print:

    cart:

    cart2:

    So the main differences between two approachs is:

    'add' & 'remove' function are only created once and are inherented (inside __proto__) if using 'prototype' approach (No2).

    For No1 approach, 'add' & 'remove' as created multi times with each instances.

    So for the performance point of view, recommended No2 approach over No1.

    But what really recommended is No3 approach:

    class Cart {
      items;
      constructor(items = []) {
        this.items = Object.freeze(items);
      }
      add(item) {
        const state = [...this.items, item];
        this.items = Object.freeze(state);
      }
      remove(id) {
        const state = this.items.filter(item => item.id !== id);
        this.items = Object.freeze(state);
      }
    }

    It is the same as No2, but with class syntax, the code is much readable and clean.

  • 相关阅读:
    linux批量远程多服务器FTP并下载文件的脚本
    NPM更换国内源
    Win10禁用无用的服务
    JS测试
    FastAdmin导出
    VScode全局设置
    Vue路由history模式
    kill_devtmpfsi
    获取域名URL
    Axios去除Respones中的config、headers、request
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13933240.html
Copyright © 2011-2022 走看看