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

演示代碼
<script>
// 給jQuery的原型添加1個方法
$.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 指向另外一個對象,該對象也具有1個 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>
生活不易,碼農辛苦
如果您覺得本網站對您的學習有所幫助,可以手機掃描二維碼進行捐贈