還記得第一次碰到 jquery 的時候,就被它的寫法吸引
想要做什麼事,一直"點"下去就可以,真的很方便,而且 code 也很容易解釋
像下面這段 code,如果沒看過 jquery ,大概還是看得出在做什麼吧
$("#p1")
.css("color", "red")
.slideUp(2000)
.slideDown(2000)
這次我用了一個"簡單的加、減法的計算"來幫助我理解這種 chain 的寫法
總共整理了 4 種做法
const calculator = () => ({
result: 0,
add: function(number) {
this.result += number
return this
},
substract: function(number) {
this.result -= number
return this
},
getResult: function() {
console.log(this.result)
return this
},
})
// 閉包
const calculator = () => {
let result = 0
return {
add: function(number) {
result += number
return this
},
substract: function(number) {
result -= number
return this
},
getResult: function() {
console.log(result)
return this
},
}
}
// return calculator(result)
const calculator = result => {
return {
add: function(number) {
const updatedResult = result + number
return calculator(updatedResult)
},
substract: function(number) {
const updatedResult = result - number
return calculator(updatedResult)
},
getResult: function() {
console.log(result)
return this
},
}
}
// class
class Calculator {
constructor(result = 0) {
this.result = result
}
add(number) {
this.result += number
return this
}
substract(number) {
this.result -= number
return this
}
getResult() {
console.log(this.result)
}
}
Understanding Method Chaining In Javascript
Javascript Function Chaining. How jQuery ruled the Web.