zl程序教程

您现在的位置是:首页 >  前端

当前栏目

[Javascript] Constructor Functions and prototype

JavaScript and prototype Functions constructor
2023-09-14 08:59:13 时间

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.