[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.
相关文章
- Win10系列:JavaScript 项目模板中的文件和项模板文件
- [Javascript] Objects and Functions
- [Javascript] Coding interview problem: Scheduler functional way
- [Rust] Load a WebAssembly Function Written in Rust and Invoke it from JavaScript
- [Javascript] Link to Other Objects through the JavaScript Prototype Chain
- [Javascript] Understand Function Composition By Building Compose and ComposeAll Utility Functions
- [Javascript] Linting JavaScript with ESLint
- [Javascript] Webpack Loaders, Source Maps, and ES6
- 分享JavaScript获取网页关闭与取消关闭的事件
- [Javascript] Constructor Functions and prototype
- [ES2019] Use JavaScript ES2019 flatMap to Map and Filter an Array
- [Rust] Pass a JavaScript Function to WebAssembly and Invoke it from Rust
- [Rust] Load a WebAssembly Function Written in Rust and Invoke it from JavaScript
- [Javascript] Combine Objects with Object.assign and Lodash merge
- [Javascript] Promise-based functions should not throw exceptions
- [Javascript] Object.freeze() vs Object.seal()
- [Immutable.js] Converting Immutable.js Structures to Javascript and other Immutable Types
- [AngularJS] Javascript scope and AngularJS $scope