首页 > 编程语言 > 详细

[Javascript] Constructor Functions and prototype

时间:2020-11-05 21:22:54      阅读:27      评论:0      收藏:0      [点我收藏+]

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.

[Javascript] Constructor Functions and prototype

原文:https://www.cnblogs.com/Answer1215/p/13933240.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!