<thead id="rrjt3"></thead>
      <progress id="rrjt3"><dfn id="rrjt3"></dfn></progress>

      <em id="rrjt3"></em>

        <address id="rrjt3"><ins id="rrjt3"><dfn id="rrjt3"></dfn></ins></address>
          <i id="rrjt3"></i>

        簡單的JS代碼封裝示例

        時間:2022-09-06 11:20:35 類型:JS/JQUERY
        字號:    

        隨著js的版本升級,現在也支持了class, 也可以直接 new 類生成一個實例對象, 封裝將變得非常簡單,那么之前的js封裝是怎么樣的呢?

        首先看一個最基礎的js封裝示例:

         function myCar() {
                this.name='莊子汽車';
                this.drive=function(){
                    console.log(this.name + "時速可以達到180KM/小時")
                }
            }
            var my = new myCar();//創建實例化對象
                console.log(my.name);//調用屬性
                my.drive();//調用方法

        這是一個非常簡單的函數封裝, 可以通過function產生獨立的作用域, 防止同名屬性的沖突, 但是在某些應用場景中還是會有一些問題, 那么我們看下下一段代碼

        index.js文件代碼:

        (function(window,$){
            function yt(name,config){
                this.name = name;
                var conf = {
                    title : "我們都是一家人",
                    content:"我們應該熱愛這個家庭",
                    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("測試");
            }
            //暴露yt方法
            window.yt = yt;
            window.tt= tt;
           
            }(window,$));
        //window是全局變量

        上面這段代碼使用的是IIFE: Immediately Invoked Function Expression, 意為立即調用的函數表達式, 也就是說, 聲明函數的同時立即調用這個函數. 這里我們可以控制想要暴露出去的屬性和方法。

        index.html文件加載

        let test = new yt("南昌雅騰",{title:"我愛我的家","keyword":"家,愛"});
                test.success();
                let max = test.getMax(100,300);
                tt();

        根據使用場景的不同,我們可以靈活選擇不同的封裝方法

        黄网站免费 <