隨著js的版本升級(jí),現(xiàn)在也支持了class, 也可以直接 new 類生成一個(gè)實(shí)例對(duì)象, 封裝將變得非常簡(jiǎn)單,那么之前的js封裝是怎么樣的呢?
首先看一個(gè)最基礎(chǔ)的js封裝示例:
function myCar() { this.name='莊子汽車'; this.drive=function(){ console.log(this.name + "時(shí)速可以達(dá)到180KM/小時(shí)") } } var my = new myCar();//創(chuàng)建實(shí)例化對(duì)象 console.log(my.name);//調(diào)用屬性 my.drive();//調(diào)用方法
這是一個(gè)非常簡(jiǎn)單的函數(shù)封裝, 可以通過(guò)function產(chǎn)生獨(dú)立的作用域, 防止同名屬性的沖突, 但是在某些應(yīng)用場(chǎng)景中還是會(huì)有一些問(wèn)題, 那么我們看下下一段代碼
index.js文件代碼:
(function(window,$){ function yt(name,config){ this.name = name; var conf = { title : "我們都是一家人", content:"我們應(yīng)該熱愛(ài)這個(gè)家庭", time : "2022-08-09", autho : "莊子", }; $.extend(conf,config); this.success = function(){ console.log(conf); } this.getMax = function(x,y){ return x > y ? x:y; } } function tt(){ console.log("測(cè)試"); } //暴露yt方法 window.yt = yt; window.tt= tt; }(window,$)); //window是全局變量
上面這段代碼使用的是IIFE: Immediately Invoked Function Expression, 意為立即調(diào)用的函數(shù)表達(dá)式, 也就是說(shuō), 聲明函數(shù)的同時(shí)立即調(diào)用這個(gè)函數(shù). 這里我們可以控制想要暴露出去的屬性和方法。
index.html文件加載
let test = new yt("南昌雅騰",{title:"我愛(ài)我的家","keyword":"家,愛(ài)"}); test.success(); let max = test.getMax(100,300); tt();
根據(jù)使用場(chǎng)景的不同,我們可以靈活選擇不同的封裝方法