$('#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