javascript鏈?zhǔn)綄懛?-只是因為看起來優(yōu)雅

$('#someElement')
    .find ("div")
    .css ("background", "red")
    .end()
    .siblings()
    .find ("div")
    .css ("background", "green")
    .show()

看慣了,很多jquery用鏈?zhǔn)秸{(diào)用是不是覺得很Cool?很優(yōu)雅?讓我們自己寫寫自己的鏈?zhǔn)胶瘮?shù)吧。看看下面簡單的demo:

  this.a = 0
}
Man.prototype.add = function (val) {
  this.a += val
  console.log(this.a)
  return this
}
let man = new Man(2)
man
  .add(1)
  .add(1)
  .add(1)

是不是覺得這樣寫起來優(yōu)雅多了?

首先顯示聲明一個函數(shù)對象,然后在函數(shù)的原型上添加一個方法,方法中添加一下操作,最后返回這個對象供下次調(diào)用。是不是覺得很簡單。話句話說只要在對象的原型鏈上添加方法,然后在方法最后返回該對象供下次調(diào)用使用。

  this.smallChickenChicken = 10
}
Man.prototype.addName = function(val) {
  this.name = val
  return this
}
Man.prototype.cut = function(val) {
  this.smallChickenChicken -= val
  return this
}
Man.prototype.saysmallChickenChicken = function() {
  console.log(`${this.name}:${this.smallChickenChicken}`)
  return this
}
let man = new Man()
man
  .addName('小雨')
  .cut(1)
  .cut(1)
  .cut(1)
  .cut(1)
  .cut(1)
  .cut(1)
  .cut(1)
  .cut(1)
  .saysmallChickenChicken()

// 小雨:2

盡情的在原型鏈上添加方法吧。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容