js函數(shù)式編程最佳實踐 - 持續(xù)更新

函數(shù)式編程最佳實踐

學習文檔


數(shù)組字串處理

function addString(el){
  return el + "0";
}
var newArr = arr.map(addString).join("");
var arr = ["1","2","3","4"];
console.log(newArr);

創(chuàng)建 tags

// 創(chuàng)建 - 單個
function createTag(val) {
    return '<div class = "dp-tag" >' + val.text + '</div>';
}
// 創(chuàng)建 - 全部,三個版本
// 1
function createAllTag(params) {
    var str = "";
    params.forEach(function (x) {
        str += createTag(x.text);
    })
    return str;
}
// 2
function createAllTag(params) {
    return params.map(function (x) {
        return createTag(x.text);
    }).join("");
}
// 3
function createAllTag(params) {
    return params.reduce(function (tags, x) {
        return tags += createTag(x.text);
    }, "");}
}
var str = createAllTag([{text:111},{text:222}]);
$("body").html(str)

創(chuàng)建表格

function createTableTd(td){
  return "<td>" + td + "</td>";
}
function createTableTr(row){
  return "<tr>" + row.map(createTableTd).join("") + "</tr>";
}
function createTable(data){
  return "<table>" + data.map(createTableTr).join("") + "</table>";
}

var data = [[1,2],[3,4]];
var res = createTable(data);
console.log(res);

實現(xiàn)一個展示/收起功能

var collectBoard = {
  dom:$("#board"),
  data:[],
  show:false,
  updateData:function(){
    this.data = [1,2,3]; 
  },
  toggle:function(){
    this.show = !this.show;
    if(this.show){
      this.updateData();
    }
    console.log(this.show,this.data);
  },
  init:function(){
    var that = this;
    this.dom.click(function(){
      that.toggle();
    })
  }
}
collectBoard.init();

傾向于對象遍歷而不是Switch語句

//傾向于對象遍歷而不是Switch語句
const fruitColor = {
  red: ['apple', 'strawberry'],
  yellow: ['banana', 'pineapple'],
  purple: ['grape', 'plum']
};

function test(color) {
  return fruitColor[color] || [];
}

只執(zhí)行一次的函數(shù)(基于隋性單例模式)

// 能用的包裝函數(shù)
var getSignle = function(fn){
  var res = null;
  return function(){
    // 理解 apply,即 fn 把傳參的權力,讓渡給了包裝函數(shù) getSignle
    return res || (res = fn.apply(this,arguments));
  }
};
var getName = function(){
  console.log(123);
  return "gs";
}
var onceGetName = getSignle(getName);
onceGetName();// 123 gs
onceGetName();// gs
onceGetName();// gs

通過高階函數(shù),傳遞 this對象值

//例一
var data = {
  domId:"wrap",
  ...
  // 通過高階函數(shù),傳遞 this.domId
  eventList:function(){
    var $domId = $("#"+this.domId);
    return {
      clickTag:function(){
        $domId.on("click","button",function(){
          $(this).remove();
        });
        this.clickTag = null;
      },
      clickToChangeFooter:function(){
        $domId.on("click","footer",function(){
          $(this).text("footer changed")
        });
        this.clickToChangeFooter = null;
      }
    }
  },
  // 不使用高階函數(shù),clickTag 函數(shù)中的this僅指向 clickTag 本身,且外層數(shù)據難以傳遞
  eventList:{
    clickTag:function(this.domId){
      $("#"+this.domId).on("click","button",function(){
        $(this).remove();
      });
      this.clickTag = null;
    }
  }
}
//例二
var obj = {
    a:1,
    b:function(){
        console.log(this)   
    }
}
// {a: 1, b: ?}
// this就是會指向最近的對象

編寫函數(shù)實現(xiàn)鏈式調用

核心就是在函數(shù)尾部,返回那個對象

var student = {
  name:"zk",
  age:19,
  setName:function(name){
    this.name = name;
    return this;
  },
  setAge:function(age){
    this.age = age;
    return this;
  }
};

student.setName("gs").setAge(22);
console.log(student);

連續(xù)使用箭頭函數(shù)

  • 只有最后是執(zhí)行,其它均為參數(shù),可以理解為柯里化
const splat = handle => (...array) => handle(array)
const fun = array => array.reduce((a, b) => a * b);
const res = splat(fun)(1, 2, 3, 4)

const add = a => b => c => a+b+c;
console.log(add(1)(2)(3))

更改一個嵌套對象數(shù)據的值

  • 利用this指向,減少引用對象層級
//這個模式,避免了出現(xiàn) dp.data.treelist = dp.data.treelist.map(...)
var obj = {
  list:{
    data:[1,2,3],
    update:function(){
    //注意,this指向父級,而不是最外層對象
      this.data = this.data.map(function(x){
        return x * x;
      })
    }
  }
}
obj.list.update()
console.log(obj);
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內容