写给自己看的. 没有什么目录和顺序
写法
new Promise() 这就是个基本的 promise
它有个 then 方法
new Promise().then();
new 的时候可以传一个异步函数
new Promise((resolve, reject) => {
// 异步函数
// 函数里的参数就是 resolve 和 reject, 表示异步请求的成功或失败
$.ajax({
url: 'http://haaaa.com/user/get_user_info.do',
type: 'post',
success(res) {
resolve(res);
},
error(err) {
reject(err);
}
});
// 异步请求写好了,接下来处理 then
// 下面 then 的两个参数分别对应 resolve 和 reject
// 如果 ajax 执行了 resolve, 走到 then 就调用第一个方法
}).then((res) => {
console.log('success', res);}, (err) => {
console.log('error', err)});
// 这两个参数对应在 then 里面也是两个方法, 通常用匿名函数来写
类
class Animal {
// 这个类有一个构造方法
constructor() {
// 可以在里面做一些属性
this.name = 'animal';
}
// 私人方法
getName() {
return this.name
}
}
let animal = new Animal();
console.log(animal) //打印出 Animal 的一个实例
console.log(animal.getName()) //打印animal
类的继承
// 类的继承
class Animal {
constructor() {
this.name = 'animal';
}
getName() {
return this.name
}
}
class Cat extends Animal {
constructor() {
super();
this.name = 'cat';
}
}
new Cat() //会报错, 因为用了 extends 关键字, 子类里没有this 对象.
// 如果想用 this, 就要在子类的构造方法里调用 super
// super 指的是父类的构造函数, 其实就是调用了 Animal 的 constructor
实例化这两个类
接上面代码
let animal = new Animal();
let cat = new Cat();
console.log(animal,getName()) //animal
console.log(cat.getName()) //cat 因为子类继承了父类的方法,在子类就可以调用父类的 getName 方法而不用再写一遍
对象的写法
var name = 'Rosen',
age = 18;
var obj = {
name: name,
age: age,
getName: function() {
return this.name;
},
getAge: function() {
return this.age;
}
}
// 上面这是老的对象的写法
Object.keys(obj); //["name","age","getName","getAge"]
// Object.assign() 和 jquery 里的 extends 比较像, 把几个对象做一个整合, 比如
Object.assign({
a:1}, {
b:2}) //执行后返回 {a: 1, b: 2}
// 还会发生覆盖, 这个过程是个浅拷贝只有第一层会覆盖, 而不会把下一层覆盖过去
ES6 模块化
主流 CommonJS, AMD, CMD 三种方案
但是他们都不是浏览器原生的, Commonjs是需要借助 nodejs 打包编译
AMD 和 CMD 都是要额外引入模块加载器
ES6 的 export 和 import
<script type="text/javascript" src="./index.js"></script>
text/javascript 这种 type 是没法模块化引入的
要改成
<script type="module" src="./index.js"></script>
才能让浏览器认识这是个模块化方式的 js
输出:
let str = 'string';
let obj = {
name: 'Rosen'
}
let fn = () => {
console.log('module test')
}
// 暴露出一个对象的形式,输出下面三个东西
export {
str,
obj,
fn
}
引入:
import {
str, obj.name, fn} from './xx.js'
export default 形式的输出和引用:
export default {
a: 1}
// export default 这种默认形式的输出的话,import 后面的名字可以随意
import haha from './xx.js';
console.log(haha) // {a:1}
as
引入:
import {
str as string, obj.name, fn} from './xx.js';
那 console.log('str': str) //就报错 str is not defined
要 console.log(string)