慕容3067478
2018-10-18 13:10:01
想問大家一個(gè)問題,為什么看到別人寫的類,屬性都掛在this上?不可以放在方法里嗎?比如function GetMusic($content) { this.content = $content; this.title = this.content.find(".title");
}
GetMusic.prototype.changTitle = function() { this.title.toggleClass("on");
}
}為什么不這樣寫function GetMusic($content) { this.content = $content;
}
GetMusic.prototype.changTitle = function() { var title = this.content.find(".title");
title.toggleClass("on");
}
}就是為什么有時(shí)候這個(gè)變量只用一次也掛在實(shí)例上,就是用this掛起來。那么其實(shí):第一種: function GetMusic($content) { this.content = $content; this.title = this.content.find(".title");
}第二種function GetMusic($content) { this.content = $content;
}
GetMusic.prototype.changTitle = function() { this.title = this.content.find(".title");
}
}第三種 function GetMusic($content) { this.content = $content;
}
GetMusic.prototype.changTitle = function() { var title = this.content.find(".title");
}
}上面的三個(gè)title變量有什么不一樣?對(duì)性能什么的有什么印象?一般什么情況下用哪種?
1 回答

qq_花開花謝_0
TA貢獻(xiàn)1835條經(jīng)驗(yàn) 獲得超7個(gè)贊
LZ你要干嘛?
對(duì)于以下:
第二種
第三種
問題:
為什么我每次調(diào)用changTitle
的時(shí)候你都給我執(zhí)行this.content.find
函數(shù)、而且每次結(jié)果都是title
,不累嗎?
對(duì)于以下:
GetMusic.prototype.changTitle = function() { var title = this.content.find(".title"); }
問題:
如果我現(xiàn)在有個(gè)其他函數(shù),叫什么changTitleColor
:
GetMusic.prototype.changTitleColor= function() { var title = this.content.find(".title"); //title.style.color = 'xxxx';} //如果保存了this.title的屬性的話就可以這樣GetMusic.prototype.changTitleColor= function() { //this.title.style.color = 'xxxx';}
上面又重復(fù)了this.content.find(".title")
這個(gè)方法,不累嗎?
其實(shí),這里要考慮的不是性能,而是封裝,也即是到底這個(gè)this.title
是不是和GetMusic
強(qiáng)相關(guān);如果是的話,那就把title給容納進(jìn)來、作為GetMusic內(nèi)部一部分;如果this.title
和GetMusic
相關(guān)性很小,那也就沒必要保存this.title
這個(gè)屬性;
也就是分清楚哪里是內(nèi)部、哪里是外部。
添加回答
舉報(bào)
0/150
提交
取消