歐羅巴皇
2017-05-26 14:47:43
?var?$?=?function?(selector)?{
????????????return?new?$.prototype.init(selector);
????????};
????????$.prototype?=?{
????????????init:?function?(selector)?{
????????????????this.el?=?document.querySelector(selector);
????????????????console.log(this)
????????????????return?this;
????????????},
????????????on:?function?(event,?fn)?{
????????????????if?(window.addEventListener)?{
????????????????????this.el.addEventListener(event,?fn,?false);
????????????????}?else?if?(window.attachEvent)?{
????????????????????this.el.attachEvent(on?+?event,?fn);
????????????????}
????????????????return?this;
????????????},
????????????attr:?function?(event,?val)?{
????????????????if?(!val)?{
????????????????????return?this.el.getAttribute(event);
????????????????}?else?{
????????????????????this.el.setAttribute(event,?val);
????????????????????return?this;
????????????????}
????????????}
????????}
????????$.prototype.init.prototype?=?$.prototype;
3 回答

hahhhha
TA貢獻(xiàn)50條經(jīng)驗(yàn) 獲得超32個(gè)贊
由于所有對(duì)象都會(huì)繼承其原型對(duì)象的屬性和方法,所以我們可以讓定義在原型對(duì)象中的那些方法都返回用以調(diào)用方法的實(shí)例對(duì)象的引用,這樣就可以對(duì)那些方法進(jìn)行鏈?zhǔn)秸{(diào)用了。
return?this;
使用回調(diào)函數(shù)從支持鏈?zhǔn)秸{(diào)用的方法獲取數(shù)據(jù)。鏈?zhǔn)秸{(diào)用很適合賦值器方法,但對(duì)于取值器方法,你可能希望他們返回你要的數(shù)據(jù)而不是this(調(diào)用該方法的對(duì)象).解決方案:利用回調(diào)技術(shù)返回所要的數(shù)據(jù).

uhelper_net
TA貢獻(xiàn)37條經(jīng)驗(yàn) 獲得超9個(gè)贊
鏈?zhǔn)綄?xiě)法,在調(diào)用的方法的函數(shù)里,返回對(duì)象(return this)即可實(shí)現(xiàn).
添加回答
舉報(bào)
0/150
提交
取消