o2.foo = 'Something different, yet again'; // 不克不及对变量再次赋值 // o2 = { message: 'I will cause an error if you uncomment me' }; // Error! // CASE 3: 对象的属性是弗成变的,然则变量可以被再次赋值。 let o3 = Object.freeze({ foo: "Can't mutate me" }); // 不克不及改变对象的属性 // o3.foo = 'Come on, uncomment me. I dare ya!'; // Error! // 照样可以对变量再次赋值 o3 = { message: "I'm some other object, and I'm even mutable -- so take that!" }; // CASE 4: 对象的属性是弗成变的,并且变量不克不及被再次赋值。这是我们想要的!!!!!!!! const o4 = Object.freeze({ foo: 'never going to change me' }); // 不克不及改变对象的属性 // o4.foo = 'talk to the hand' // Error! // 不克不及对变量再次赋值 // o4 = { message: "ain't gonna happen, sorry" }; // Error 不变性实用于所有的数据构造,包含数组、映射和集合。它意味着不克不及调用例如 Array.prototype.push 等会导致本身改变的办法,因为它会改变已经存在的数组。可以经由过程创建一个含有本来元素和新加元素的新数组,而不是将新元素参加一个已经存在的数组。其实所有会导致数组本身被修改的办法都可以经由过程一个返回修改好的新数组的函数代替。
摸索函数式编程,经由过程它让你的法度榜样更具有可读性和易于调试
- 'use strict';
- const a = Object.freeze([4, 5, 6]);
- // Instead of: a.push(7, 8, 9);
- const b = a.concat(7, 8, 9);
- // Instead of: a.pop();
- const c = a.slice(0, -1);
- // Instead of: a.unshift(1, 2, 3);
- const d = [1, 2, 3].concat(a);
- // Instead of: a.shift();
- const e = a.slice(1);
- // Instead of: a.sort(myCompareFunction);
- const f = R.sort(myCompareFunction, a); // R = Ramda
- // Instead of: a.reverse();
- const g = R.reverse(a); // R = Ramda
- // 留给读者的演习:
- // copyWithin
- // fill
- // splice
- const map = new Map([
- [1, 'one'],
- [2, 'two'],
推荐阅读
如何处理JavaScript内存泄露
沙龙晃荡 | 去哪儿、陌陌、ThoughtWorks在主动化运维中的实践!10.28不见不散!
几周前,我们开端写一个系列,>>>详细阅读
本文标题:JavaScript的函数式编程,你了解吗?
地址:http://www.17bianji.com/lsqh/38230.html
1/2 1