jQuery 的 $.fn 可以防止 jQuery 的原型被篡改
來源:程序員人生 發(fā)布時(shí)間:2015-04-24 08:14:00 閱讀次數(shù):3343次
$.fn 和 $.prototype 都指向 jQuery 的原型,由于 $.fn 的存在,即便 $.prototype 被修改指向另外一個(gè)對(duì)象,jQuery 的實(shí)際原型還在,不會(huì)被篡改。

演示代碼
<script>
// 給jQuery的原型添加1個(gè)方法
$.fn.extend({
im : function(){
console.log("Hi, I am prototype");
console.log("-----");
}
});
console.log($.fn === $.prototype); // true
$.prototype.im.call(document.querySelector('body'), null); // "Hi, I am prototype"
$('body').im(); // "Hi, I am prototype"
//將 $.prototype 指向另外一個(gè)對(duì)象,該對(duì)象也具有1個(gè) im 方法
$.prototype = {
im : function(){
console.log("Hi, I've changed");
console.log('------');
}
};
console.log($.fn === $.prototype); //flase
$.prototype.im.call(document.querySelector('body'), null); // "Hi, I've changed" 改變了
$('body').im(); // "Hi, I am prototype" 沒有改變
</script>
生活不易,碼農(nóng)辛苦
如果您覺得本網(wǎng)站對(duì)您的學(xué)習(xí)有所幫助,可以手機(jī)掃描二維碼進(jìn)行捐贈(zèng)