ES6学习(模块化,类)

ES6学习(模块化)

大家都知道js不支持模块化,像ruby有require,python有import

在ES6出现之前,社区也制定了一套模块规范,
CommonJS require(‘http’) 还有AMD,CMD等其他规范

ES6出现后,一统服务端和客户端的模块规范

我们这样定义和使用模块(注意要在localhost)

export const a = 10;
export {
	temp as t,
	a as num
}

<script type="module">
		import './modules/1.js'; 
		import {t as temp, num as i_num} from './modules/2.js'
		import * as modTwo from './modules/2.js';
</script>

像这样引入是不可以加入代码逻辑的,如果想使用代码逻辑来引入js,例如条件判断,这时候我们要选择import(),它返回一个promise对象

import('./common.js').then(res=>{
	console.log(res.a)
})

想想我们之前在js中是怎样定义类的,其实就是定义方法

            function Person(name,age){
                this.name = name;
                this.age = age;
            }

            Person.prototype.showName = function(){
                return `名字为 ${this.name}`
            }

            let p = new Person('Peter',18);
            
            console.log(p.showName());

ES6是怎么写的呢?

    <script>
        class Person {
            constructor(name,age){
            	this.name = name;
                console.log(name,age)
            }
        }
        showName(){
			console.log(this.name)
		}

        let p = new Person('Peter',21);
    </script>

其实本质还是function,我们可以typeof 出来
下面我们介绍一下get,set

<script>
        class Person {
            constructor(name,age){
                console.log(name,age)
            }
            set test(val){
                alert(val)
            }

            get test(){
                return 'get'
            }
        }

        let p = new Person('Peter',21);
        p.test = "666"
        console.log(p.test)
    </script>

平时我也很少用到,大家作为了解,

继承

说到类,就不得不提到继承
----- 如果用以前的方法,就不得不设置this
矫正this:
1. fn.call(this指向谁, args1, args2…)
2. fn.apply(this指向谁, [args1, args2…])
3. fn.bind()

到了ES6,简直是不要再轻松----- extends 和java一样
在子类的构造函数中不要忘记调用super()

下一次写个拖拽的小栗子

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章