JS中常用的封裝函數4種方法:
1. 函數封裝法:
function box(){ }
2. 封裝成對象 :
let Cookie = { get(){ }, set(){ } }
3. 封裝成構造函數:
function Dog(){ }
4. 類的方法:
class Person{ constructor(){ } show(){ } }
jQuery中常見的封裝函數方法:
方法一:
$.extend({ log(s){ console.log(s)//封裝了打印函數 } })
方法二:
$.fn.mytest = function(){ console.log(this,1111)//this 偽數組 this.css({color:'yellow'}) } $('div').mytest()//指出哪個選擇器調用這個函數
方法三:也可以在原型函數上添加,例如:
var arr = [1,2,3] // arr.map(function(){}) Array.prototype.myMap = function(fn){ //原型上添加 } arr.myMap(function(){ //數組上直接調用這個函數 })
歡迎大家多多交流,如有疑問可以在博客上問我哦~