js编程的一些小技巧

2019-12-07  本文已影响0人  Mcq

1.用闭包保护对象属性

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
  }
}

  1. 函数式编程:了解命令式代码的危害

典型的命令式代码就是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.用函数式编程避免副作用

函数式编程的核心原则之一是不更改值。
改变函数参数和全局变量被称为突变,其结果被称为副作用。
以传参的方式避免函数内部对外依赖

上一篇 下一篇

猜你喜欢

热点阅读