js 模塊化 -- 基本的導出與引入class模塊


1.目錄結構

 

 

 2.類語法與導出

class food {
}

//定義常量
let c = "蘋果";
//正確的函數寫法
food.prototype.getfood = function (str) {
    if (!str) {
        return "" + this.g;
    }
    return "" + str
}
//定義常量
food.prototype.g = "荔枝";



class food2 {
    //定義常量
    c2 = "蘋果";
    //無法這個定義函數,錯誤寫法
    // function kk(){
    //
    // }
    //正確的函數寫法
    getfood2 = function (str) {
        if (!str) {
            return "" + c;
        }
        return "" + str
    }
}


//默認導出 ,如果事由一個類用這個方法修方便,
// export {food as default };
export {food, food2}
源碼

寫了兩種定義類方法和屬性變量的寫法

注意:類名.prototype.【變量名或者方法】=  。。。這種寫法是擴展寫法,
或者說prototype就是用於擴展類里的變量名或者方法的

3.html 導入 與使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>組件引入測試</title>
<!--    &lt;!&ndash;導入腳本&ndash;&gt;-->
<!--    <script type="text/javascript" src="../../../plug/vue/devVue.js"></script>-->
<!--    &lt;!&ndash;導入樣式&ndash;&gt;-->
<!--    <link rel="stylesheet" type="text/css" href="../../../css/myStyle.css">-->
<!--    &lt;!&ndash;layui 界面組件&ndash;&gt;-->
<!--    <link rel="stylesheet" type="text/css" href="../../../plug/layui/css/layui.css">-->
</head>
<body>
<div id="aut">


</div>

<!--模塊加載需要將類型設置為module-->
<script type="module" >

    //http://localhost:57/html/pc/test/h1.html

    //正常導入類
    import {food,food2} from "./js/classTest1.js"
    //導入類換別名
    // import {food as f,food2 as f2} from "./js/classTest1.js"
    console.log(food)
    let c_food = new food();
    console.log(c_food.getfood())
    console.log(c_food.getfood("西瓜"))
    console.log(c_food.g)
    // console.log(mc.getfood())
    // console.log(mc.getfood("西瓜6655東方航空"))
    let c_food2 = new food2();
    console.log(c_food2.c2)
    console.log(c_food2.getfood2())
    console.log(c_food.getfood("芒果"))

</script>

</body>
</html>
源碼

核心部分是

 

 

 4.測試

打印結果如下

 

 

 5.跨域提示

靜態文件要么放在工程里、要么放在.net站點、要么配置nginx路由到本地的靜態文件、要么修改瀏覽器的權限,否則會報CROS跨域異常

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM