1.Use Closure to Protect Properties Within an Object from Being Modified Externally(用闭包保护对象属性)
The simplest way to make this public property private is by creating a variable within the constructor function.
function Bird() {
let weight = 15
this.getWeight = function () {
return weight
}
}
2.Functional Programming: Understand the Hazards of Using Imperative Code(函数式编程:了解命令式代码的危害)
典型的命令式代码就是for循环,它明确的指定操作数组的下标。
相反的,函数式编程通过函数告诉计算机你希望的操作。比如与for对应的map,filter相关操作。
这有助于避免语义错误,比如调试一节中提到的“Off By One error”。
example
// tabs is an array of titles of each site open within the window
var Window = function(tabs) {
this.tabs = tabs; // we keep a record of the array inside the object
};
// When you join two windows into one window
Window.prototype.join = function (otherWindow) {
this.tabs = this.tabs.concat(otherWindow.tabs);
return this;
};
// When you open a new tab at the end
Window.prototype.tabOpen = function (tab) {
this.tabs.push('new tab'); // let's open a new tab for now
return this;
};
// When you close a tab
Window.prototype.tabClose = function (index) {
// Only change code below this line
var tabsBeforeIndex = this.tabs.slice(0, index); // get the tabs before the tab
var tabsAfterIndex = this.tabs.slice(index + 1); // get the tabs after the tab
this.tabs = tabsBeforeIndex.concat(tabsAfterIndex); // join them together
// Only change code above this line
return this;
};
// Let's create three browser windows
var workWindow = new Window(['GMail', 'Inbox', 'Work mail', 'Docs', 'freeCodeCamp']); // Your mailbox, drive, and other work sites
var socialWindow = new Window(['FB', 'Gitter', 'Reddit', 'Twitter', 'Medium']); // Social sites
var videoWindow = new Window(['Netflix', 'YouTube', 'Vimeo', 'Vine']); // Entertainment sites
// Now perform the tab opening, closing, and other operations
var finalTabs = socialWindow
.tabOpen('new tab') // Open a new tab for cat memes
.join(videoWindow.tabClose(2)) // Close third tab in video window, and join
.join(workWindow.tabClose(1).tabOpen('new tab'));
console.log(finalTabs.tabs)
3.Avoid Mutations and Side Effects Using Functional Programming
函数式编程的核心原则之一是不更改值。
改变函数参数和全局变量被称为突变,其结果被称为副作用。
Pass Arguments to Avoid External Dependence in a FunctionPassed
以传参的方式避免函数内部对外依赖
So far, we have seen two distinct principles for functional programming:
-
Don't alter a variable or object - create new variables and objects and return them if need be from a function.
-
Declare function arguments - any computation inside a function depends only on the arguments, and not on any global object or variable.
网友评论