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.

  • 相关阅读:
    Asp.net core中间件实现原理及用法解说
    C#中,async关键字到底起什么作用?
    C# 中的Async 和 Await 的用法详解
    .NET委托,事件和Lambda表达式
    docker push到私有仓库 docker push 镜像到harbor
    shell tput的用法
    Shell中获取脚本的绝对路径$( cd "$( dirname "$0" )" && pwd)
    shell脚本中 "set -e" 的作用
    从旧goadddy账号转移域名到新的goaddy账号中
    git制作patch的步骤
  • 原文地址:https://www.cnblogs.com/Answer1215/p/13933240.html
Copyright © 2011-2022 走看看