代码示例:https://github.com/lotapp/BaseCode/tree/master/javascript/1.ES6javascript
在线演示:https://github.lesschina.com/js/1.base/ES6与PY3.htmlcss
ES6如今浏览器基本上都支持了,能够收一波韭菜了~(关键移动端都支持了)html
var
:能够重复定义,不能限制修改,没有块级做用域(和Python差很少)let
:不能够重复定义,至关于C#的变量,块级做用域(之后var所有换成let)const
:不能够重复定义,至关于C#的常量,块级做用域1.var能够重复定义前端
var a1 = 12; // 定义了一个a变量
// ...写了若干代码
var a1 = 5; // 而后又从新定义了一个a,这时候可能就有潜在bug了
console.log(a1); // 5
2.let不能够重复定义,至关于C#的变量(之后var所有换成let)java
let a2 = 12;
let a2 = 5;
// 标识符a已经被声明
console.log(a2); // Identifier 'a2' has already been declared
3.const:不能够重复定义,至关于C#的常量react
const a3 = 12;
const a3 = 5;
// 标识符a已经被声明
console.log(a3); // Identifier 'a3' has already been declared
1.var
能够修改git
var a = 2;
a = 3;
// var 能够修改
console.log(a); //3
2.let
能够修改github
let b = 2;
b = 3;
// let能够修改
console.log(b);
3.const
不能够修改ajax
const c = 12;
c = 5;
// 不能赋值给常量变量
console.log(c); // Assignment to constant variable.
1.var没有块级做用域npm
if(1<2){
var b1 = 1;
}
// var没有块级做用域
console.log(b1); // 1
2.let复合正常变量特性
// 和咱们平时使用差很少了
if(1<2){
let b2 = 1;
}
// ReferenceError: b2 is not defined
console.log(b2); // b2 没有定义
3.更严格的const就更不说了
if(1<2){
const b3 = 1;
}
// ReferenceError: b3 is not defined
console.log(b3); // b3 没有定义
变量没有修饰符的,直接定义,全局变量global
引用便可
1.var变量和Python相似
if 1 < 2:
b = 1
print(b) # 1
2.全局变量建议global
引用一下
age = 20
def test():
global age
print(age) # 20
var
所有换成let
)¶var
:能够重复定义,不能限制修改,没有块级做用域(和Python差很少)let
:不能够重复定义,至关于C#的变量,块级做用域(之后var所有换成let)const
:不能够重复定义,至关于C#的常量,块级做用域这个特性不论是C#
仍是ES6
都是从Python
那借鉴过来的,特色:
简单版:
let [a,b,c] = [1,2,3];
console.log(a,b,c); // 1 2 3
变化版:
let {a,b,c} = {a:1,b:2,c:3}; // json格式对应也行
console.log(a,b,c); // 1 2 3
PS:把后面改为{a1:1,b1:2,c1:3}
就变成undefined undefined undefined
复杂版:
let [x, { a, b, c }, y] = [4, { a: 1, b: 2, c: 3 }, 5];
console.log(a, b, c, x, y); // 1 2 3 4 5
左右两边结构须要同样
// 这种就不行,格式得对应(左边3,右边5个 ==> over)
let [x, { a, b, c }, y] = { a: 1, b: 2, c: 3, x: 4, y: 5 };
console.log(a, b, c, x, y); // 未捕获的TypeError:{...}不可迭代
定义和赋值同时完成
let [a, b, c];
[a, b, c] = [1, 2, 3];
// 未捕获的SyntaxError:在解构声明中缺乏初始化程序
console.log(a, b, c);
之前写法:
function (参数,参数){
函数体
}
简化写法:
(参数,参数) => {
函数体
}
参数 => {
函数体
}
参数 => 表达式
举个例子:
function add(x, y) {
return x + y;
}
let add1 = function (x, y) {
return x + y;
}
let add2 = (x, y) => {
return x + y;
}
let add3 = (x,y) => x+y;
console.log(add(1, 2)); // 3
console.log(add1(1, 2)); // 3
console.log(add2(1, 2)); // 3
console.log(add3(1, 2)); // 3
和Net用起来基本上同样
)¶()
能够省略
let get_age = age => {
return age - 2;
}
console.log(get_age(18)); // 16
{}
能够省略
return
,那么return
也能够省略
let get_age = age => age - 2;
console.log(get_age(18)); // 16
return
也能够简写
let print_age = age => console.log(age - 2);
print_age(18); // 16
PS:箭头函数会改变this
(后面会说)
// 原来:
function show(a, b, c) {
c = c || 7; // 默认参数
console.log(a, b, c);
}
// 如今:
function show(a, b, c = 7) {
console.log(a, b, c);
}
show(1, 2); // 1 2 7
show(1, 2, 3); // 1 2 3
举个例子:
let show_args = (a, b, ...args) => console.log(a, b, args);
// `...args`是个数组(Python是元组)
show_args(1, 2, 3, 4, 5, 6);// 1 2 [3, 4, 5, 6]
...args
必须是最后一个参数
let show_args = (a, b, ...args, c) => console.log(a, b, args, c);
// Uncaught SyntaxError: Rest parameter must be last formal parameter
show_args(1, 2, 4, 5, 6, c = 3); // ...args必须是最后一个参数
PS:Python里面能够:
def show(a, b, *args, c):
print(a, b, args, c)
# 1 2 (4, 5, 6) 3
show(1, 2, 4, 5, 6, c=3)
案例1:
let nums = [1, 2, 3, 4];
// 解包使用
let nums2 = [0, ...nums, 5, 6];
// [0,1,2,3,4,5,6]
console.log(nums2);
PS:Python用法相似:
# 列表换成元组也同样用
num_list = [1,2,3,4]
# 不论是列表仍是元组,这边须要加*才能解包
num_list2 = [0,*num_list,5,6]
# [0, 1, 2, 3, 4, 5, 6]
print(num_list2)
案例2:
let nums = [1, 2, 3, 4];
let nums2 = [0, 5, 6];
nums.push(...nums2);
// [1, 2, 3, 4, 0, 5, 6]
console.log(nums);
PS:Python用法相似:
num_list = [1,2,3,4]
num_list2 = [0,5,6]
# [1, 2, 3, 4, 0, 5, 6]
num_list.extend(num_list2)
print(num_list)
# 若是使用append就是嵌套版列表了
# num_list.append(num_list2)
# [1, 2, 3, 4, [0, 5, 6]]
普通函数的this ==> 谁调用就是谁(常常变:谁调用是谁)
function show() {
alert(this); // 1,2,3,4
console.log(this); // [1, 2, 3, 4, show: ƒ]
}
let arr = [1, 2, 3, 4];
arr.show = show;
arr.show();
箭头函数的this ==> 在谁的环境下this
就是谁(不变:当前做用域)
let arr = [1, 2, 3, 4];
arr.show = () => {
alert(this); // [object Window]
console.log(this); // Window
}
arr.show();
再举个例子:在document内
document.onclick = function () {
let arr = [1, 2, 3, 4];
arr.show = () => {
console.log(this); // document
}
arr.show();
}
下面几个方法都不会改变原数组
映射,传几个参数进去,出来几个参数。(不改变数组内容,生成新数组)
scor_arr = [100, 28, 38, 64]
let results = scor_arr.map(item => item >= 60);
// [true, false, false, true]
console.log(results); // 不改变scor_arr内容,生成新数组
// old:
// let results = scor_arr.map(function (item) {
// return item >= 60;
// });
Python略有不一样:(把函数依次做用在list的每一个元素上
)
scor_list = [100, 28, 38, 64]
result_list = map(lambda item: item >= 60, scor_list)
# [True, False, False, True] 不改变旧list的值
print(list(result_list))
PS:result_list:PY2直接返回list,PY3返回Iterator
代言词:过滤(不改变数组内容,生成新数组)
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
nums2 = nums.filter(item => item % 2 == 0);
// [2, 4, 6, 8, 10]
console.log(nums2) // 不改变旧数组的值
Python略有不一样:(把函数依次做用在list的每一个元素上
)
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
nums2 = filter(lambda item: item % 2 == 0, nums)
# [2, 4, 6, 8, 10] 不改变旧list的值
print(list(nums2))
PS:nums2:PY2直接返回list,PY3返回Iterator
不作任何修改,纯粹的遍历,用法和net
里面的ForEach
差很少
forEach
没有返回值的验证¶nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let sum = 0;
let temp =nums.forEach(item => {
sum += item;
});
console.log(sum) // 55
console.log(temp) // 验证了:forEach 没有返回值
NetCore:
var sum = 0;
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
list.ForEach(item => sum += item);
Console.WriteLine(sum); // 55
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
nums.forEach(item => {
item += 1;
});
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
console.log(nums); //不会改变nums,仅仅是遍历
NetCore:
var list = new List<int>() { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
list.ForEach(item => item += 1);
foreach (var item in list)
{
// 12345678910
Console.Write(item); //不会改变list里面的值
}
代言词:汇总,和map
有点相反,进去一堆出来一个
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
// x是第一个元素,y是第二个元素
nums.reduce((x, y, index) => {
console.log(x, y, index);
});
输出:
1 2 1 undefined 3 2 undefined 4 3 undefined 5 4 undefined 6 5 undefined 7 6 undefined 8 7 undefined 9 8 undefined 10 9
逆推整个执行过程:
简单说就是按顺序依次执行函数,eg:
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
result = nums.reduce((x, y) => x + y);
console.log(result / nums.length) // 5.5
reduce直接求平均值:(return是关键)
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let result = nums.reduce((temp, item, index) => { temp += item; if (index < nums.length - 1) { return temp; } else { // 最后一次,返回平均值便可 return temp / nums.length; } }); console.log(result) // 5.5
reduce就两个参数(有且仅有
)
Python
的Reduce
没js
的强大,通常都是对列表作一个累积的‘汇总’操做
import functools
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = functools.reduce(lambda x, y: x + y, nums)
print(result / len(nums)) # 5.5
能够看看执行过程:
import functools
nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
result = functools.reduce(lambda x, y: print(x, y), nums)
print(result)
输出:
1 2 None 3 None 4 None 5 None 6 None 7 None 8 None 9 None 10 None
通俗讲:把类数组集合转化成数组
HTML代码:/BaseCode/javascript/1.ES6/1.array.from.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Array.from的应用</title>
</head>
<body>
<style type="text/css">
div {
width: 200px;
height: 200px;
margin-right: 1px;
float: left;
}
</style>
<div></div>
<div></div>
<div></div>
</body>
</html>
JS部分:(collection是没有forEach方法的,须要转化成数组)
window.onload = () => {
let collection = document.getElementsByTagName("div");
Array.from(collection).forEach(item => item.style.background = "blue");
}
let [a, b] = [1, 2];
json = { a, b, c: 3 };
console.log(json); // {a: 1, b: 2, c: 3}
// 原来写法
// json = { a: a, b: b, c: 3 };
json = {
a: 1,
b: 2,
show() {
console.log(this.a, this.b);
}
};
json.show(); // 1 2
// 原来写法
// json = {
// a: 1,
// b: 2,
// show: function () {
// console.log(this.a, this.b);
// }
// };
Json
字符串的标准写法:
let str1 = '{ a: 12, b: 5 }'; // 错误
let str2 = '{ "a": 12, "b": 5 }';// 正确
let str3 = "{ 'a': 'abc', 'b': 5 }";// 错误(单引号)
let str4 = '{ "a": "abc", "b": 5 }';// 正确(双引号)
// 测试是否为字符串
[str1, str2, str3, str4].forEach(str => {
try {
let json = JSON.parse(str);// 转换成JSON对象
console.log(json);
} catch (ex) {
console.log(`字符串:${str}转换发生异常:${ex}`);
}
});
输出:
字符串:{ a: 12, b: 5 }转换发生异常:SyntaxError: Unexpected token a in JSON at position 2 1.base.json.html:21 {a: 12, b: 5} 1.base.json.html:23 字符串:{ 'a': 'abc', 'b': 5 }转换发生异常:SyntaxError: Unexpected token ' in JSON at position 2 1.base.json.html:21 {a: "abc", b: 5}
字符串和Json相互转换:
JSON.parse()
JSON.stringify()
let json1 = { name: "小明", age: 23, test: "我X!@#$%^&*(-_-)=+" };
let new_str = JSON.stringify(json1);
console.log(new_str);
// encodeURI对有些特殊符号并不会编码替换
let urlstr = encodeURIComponent(`https://www.baidu.com/s?wd=${new_str}`);
console.log(urlstr);
console.log(decodeURIComponent(urlstr));
输出:
{"name":"小明","age":23,"test":"我X!@#$%^&*(-_-)=+"} https://www.baidu.com/s?wd=%7B%22name%22:%22%E5%B0%8F%E6%98%8E%22,%22age%22:23,%22test%22:%22%E6%88%91X!@#$%25%5E&*(-_-)=+%22%7D https%3A%2F%2Fwww.baidu.com%2Fs%3Fwd%3D%7B%22name%22%3A%22%E5%B0%8F%E6%98%8E%22%2C%22age%22%3A23%2C%22test%22%3A%22%E6%88%91X!%40%23%24%25%5E%26*(-_-)%3D%2B%22%7D https://www.baidu.com/s?wd={"name":"小明","age":23,"test":"我X!@#$%^&*(-_-)=+"}
省的一个个去拼接了(PS:反单引号
)
let [name,age]=["小明",23];
// 我叫小明,我今年23
console.log(`我叫${name},我今年${age}`);
Python3用起来差很少:
name, age = "小明", 23
# 我叫小明,今年23
print(f"我叫{name},今年{age}")
注意一点:换行内容若是不想要空格就顶行写
console.log(`我叫:
小明
今年:
23`);
输出:
我叫: 小明 今年: 23
Python就换成了"""
print("""我叫:
小明
今年:
23
""")
let url = "https://www.baidu.com";
if (url.startsWith("http://") || url.startsWith("https://")) {
console.log("B/S");
}
if (url.endsWith(".com")) {
console.log(".com")
}
url = "https://www.baidu.com"
if url.startswith("https://") or url.startswith("http://"):
print("B/S")
if url.endswith(".com"):
print(".com")
参考文档:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Classes
之前JS的OOP严格意义上仍是一个个函数,只是人为给他含义罢了,如今是真的支持了,性能和语法都优化了
// People后面没有括号
class People {
// 构造函数
constructor(name, age) {
this.name = name;
this.age = age;
}
show() {
console.log(`我叫:${this.name},今年${this.age}`);
}
// 静态方法
static hello() {
console.log("Hello World!");
}
}
// new别忘记了
let xiaoming = new People("小明", 23);
xiaoming.show(); //我叫:小明,今年23
// xiaoming.hello(); 这个不能访问(PY能够)
People.hello(); //Hello World!
看看Python怎么定义的:(self每一个都要写)
class People(object):
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print(f"我叫:{self.name},今年:{self.age}")
@classmethod
def hello(cls):
print("Hello World!")
xiaoming = People("小明", 23)
xiaoming.show() # 我叫:小明,今年:23
# 这个虽然能够访问到,但我一直都不建议这么用(否则用其余语言会混乱崩溃的)
xiaoming.hello() # Hello World!
People.hello() # Hello World!
PS:JS后来居上,看起来语法比PY更简洁点了
class Teacher extends People {
constructor(name, age, work) {
super(name, age); // 放上面
this.work = work;
}
show_job() {
console.log(`我是作${this.work}工做的`);
}
}
let xiaozhang = new Teacher("小张", 25, "思想教育");
xiaozhang.show(); // 我叫:小张,今年25
xiaozhang.show_job(); // 我是作思想教育工做的
Teacher.hello(); // Hello World!
PS:若是子类中存在构造函数,则须要在使用
this
以前首先调用super()
看看Python语法:
class Teacher(People):
def __init__(self, name, age, work):
self.work = work
super().__init__(name, age)
def show_job(self):
print(f"我是作{self.work}工做的")
xiaozhang = Teacher("小张", 25, "思想教育")
xiaozhang.show() # 我叫:小张,今年:25
xiaozhang.show_job() # 我是作思想教育工做的
Teacher.hello() # Hello World!
多态这方面和Python同样,有点后劲不足,只能伪实现,不能像Net、Java这些这么强大
class Animal {
constructor(name) {
this.name = name;
}
run() {
console.log(`${this.name}会跑`);
}
}
class Dog extends Animal {
run() {
console.log(`${this.name}会飞快的跑着`);
}
}
// 借助一个方法来实现多态
let run = obj => {
obj.run()
}
run(new Animal("动物")); // 动物会跑
run(new Dog("小狗")); // 小狗会飞快的跑着
Python也半斤八两,十分类似
class Animal(object):
def __init__(self, name):
self.name = name
def run(self):
print(f"{self.name}会跑")
class Dog(Animal):
def run(self):
print(f"{self.name}会飞快的跑着")
# 借助一个方法来实现多态
def run(obj):
obj.run()
run(Animal("动物")) # 动物会跑
run(Dog("小狗")) # 小狗会飞快的跑着
bind
¶直接指定函数中
this
的值,防止改变
若是指定一个事件执行函数的时候,class里面的this会变化,这时候不想外面套一层方法就可使用bind
class People {
constructor(name, age) {
this.name = name;
this.age = age;
}
show() {
console.log(this);
console.log(`我叫:${this.name},今年${this.age}`);
}
}
let p = new People("小明", 23);
// 按照道理应该能够,可是由于this变了,因此不行
//document.onclick = p.show; // 我叫:undefined,今年undefined
// 原来写法:外面包裹一层方法
//document.onclick = () => p.show(); // 我叫:小明,今年23
// 简写:bind
document.onclick = p.show.bind(p); // 我叫:小明,今年23
小验证:直接指定函数中this
的值,防止改变
function show() {
console.log(this);
}
document.onclick = show; // document
document.onclick = show.bind("mmd"); // String {"mmd"}
小验证:箭头函数的优先级比bind高
document.onclick = function () {
let arr = [1, 2, 3, 4];
arr.show = () => {
console.log(this); // document
}
arr.show.bind("mmd"); // 箭头函数的优先级比bind高
arr.show();
}
课后拓展:https://www.jianshu.com/p/5cb692658704
Python3 与 C# 面向对象之~封装: http://www.javashuo.com/article/p-purcxavn-d.html
Python3 与 C# 面向对象之~继承与多态: http://www.javashuo.com/article/p-ticxscaz-cv.html
微信小程序出来后,组件化的概念愈来愈火(能够理解为模块化),结合OOP
真的很方便
先看个React
的基础案例(结合Next.js
更爽)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>React组件化</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/react/16.6.3/react.production.min.js"></script>
<script src="./js/react-dom/16.6.3/react-dom.production.min.js"></script>
<script src="./js/babel-core/5.8.38/browser.min.js"></script>
<!-- 注意下类型是"text/babel" -->
<script type="text/babel">
window.onload=function () {
let item = document.getElementById("test");
ReactDOM.render(
<strong>公众号:逸鹏说道</strong>,
item
);
};
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
输出:公众号:逸鹏说道
业余扩展:AMD
、CMD
、CJS
、UMD
: https://blog.csdn.net/yikewang2016/article/details/79358563
PS:React 16.x
开始:
react.js
==> react.development.js
react.min.js
==> react.production.min.js
react-dom.js
==> react-dom.development.js
react-dom.min.js
==> react-dom.production.min.js
PS:若是本身找JS,搜索三个包:react
、react-dom
、babel-core 5.x
(JSX)
npm国内镜像:https://npm.taobao.org
配置一下便可:npm install -g cnpm --registry=https://registry.npm.taobao.org
而后就能够把cnpm
看成npm
来用了,好比上面三个js文件:
cnpm install react
cnpm install react-dom
cnpm i babel-core@old
PS:i
是install
的简写,-g
是安装到全局环境中,不加就只是安装到当前目录
用OOP
来改造一下上面的案例:(ReactDOM
在执行render
渲染<MyTest>
标签的时候会返回,MyTest类
里面的return值
)
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>OOP组件</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/react/16.6.3/react.production.min.js"></script>
<script src="./js/react-dom/16.6.3/react-dom.production.min.js"></script>
<script src="./js/babel-core/5.8.38/browser.min.js"></script>
<script type="text/babel">
class MyTest extends React.Component{
// 能够省略
constructor(...args){
super(...args);
}
// 必须定义的方法
render(){
return <strong>公众号:逸鹏说道</strong>;
}
}
window.onload=()=>{
let test = document.getElementById("test");
ReactDOM.render(
<MyTest></MyTest>,
test
);
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
输出:公众号:逸鹏说道
好处经过这个案例可能还看不出来,可是你想一下:当那些经常使用功能模板成为一个个本身的组件时,你的每一次前端开发是多么幸福的事情?
再语法衍生一下,来个稍微动态一点案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>OOP组件</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/react/16.6.3/react.production.min.js"></script>
<script src="./js/react-dom/16.6.3/react-dom.production.min.js"></script>
<script src="./js/babel-core/5.8.38/browser.min.js"></script>
<script type="text/babel">
class Item extends React.Component{
render(){
console.log(this);
return <strong>{this.props.str}</strong>;
}
}
window.onload=()=>{
ReactDOM.render(<Item str="我叫小明"></Item>,document.getElementById("test"));
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
输出:(两种方式传参:1.字符串,2.{}表达式)
有上面两个铺垫,如今作个本身的小组件:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>OOP组件</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="./js/react/16.6.3/react.production.min.js"></script>
<script src="./js/react-dom/16.6.3/react-dom.production.min.js"></script>
<script src="./js/babel-core/5.8.38/browser.min.js"></script>
<script type="text/babel">
class Item extends React.Component{
render(){
console.log(this);
return <li><strong>{this.props.str}</strong></li>;
}
}
class MyList extends React.Component{
render(){
console.log(this);
return <ul>
{this.props.names.map(x=> <Item str={x}></Item>)}
</ul>
}
}
window.onload=()=>{
let test = document.getElementById("test");
ReactDOM.render(
// 这边的值能够从后台获取
<MyList names={["Golang","Python","NetCore","JavaScript"]}></MyList>,
test
);
}
</script>
</head>
<body>
<div id="test"></div>
</body>
</html>
输出:(两种方式传参:1.字符串,2.{}表达式)
课后拓展:https://www.babeljs.cn/learn-es2015/
最后方案和写法相似于Python
、NetCore
,都是async
和await
,前面是一步步引入(本质)
基于JQ
的异步操做很常见,好比:
console.log("--------------------")
$.ajax({
url: "./data/user.json",
dataType: "json",
success(data) {
console.log(data);
}, error(ex) {
console.log("请求失败");
}
});
console.log("--------------------")
输出:(的确是异步操做,不等结果返回就先执行下面语句了)
-------------------- -------------------- {Name: "小明", Age: 23}
那么它的本质是什么呢?来看看返回什么:
let p1 = $.ajax({
url: "./data/user.json",
dataType: "json"
});
console.log(p1);
输出:(其实本质也是一个封装版的Promise
)
用等价写法改装一下:(then两个方法,一个处理成功,一个处理失败
)
let p1 = \$.ajax({
url: "./data/user.json",
dataType: "json"
});
// 不存在的文件
let p2 = \$.ajax({
url: "./data/mmd.json",
dataType: "json"
});
p1.then(data => console.log(data), ex => console.log("请求失败"));
p2.then(data => console.log(data), ex => console.log("请求失败"));
输出:(忽略上面的\
个人渲染有的问题,须要转义一下)
{Name: "小明", Age: 23} 请求失败
简单的说就是:Promise:用同步的方式去写异步
语法:Promise(()=>{});
有点相似于NetCore
的Task
==> Task.Run(()=>{});
上面的那个例子本质上至关于:
let p1 = new Promise((resolve, reject) => {
$.ajax({
url: "./data/user.json",
dataType: "json",
success(data) {
resolve(data);
},
error(ex) {
reject(ex);
}
});
});
p1.then(data => console.log(data), ex => console.log("请求失败"));
业务上不免都有相互依赖,之前写法也只能在sucess
回调函数里面一层层的嵌套
一个是比较麻烦,还有就是看起来特别不方便,一不当心就搞错了,如今就简单多了,then里面直接处理
咋一看,没啥好处啊?并且还复杂了,其实当任务多的时候好处就来了
好比结合JQ来模拟一个事务
性的案例:
let p1 = $.ajax({ url: "./data/user.json", dataType: "json" });
let p2 = $.ajax({ url: "./data/list.txt", dataType: "json" });
let p3 = $.ajax({ url: "./data/package.json", dataType: "json" });
// 进行一系列处理(有一个失败都会直接进入错误处理)
Promise.all([p1, p2, p3]).then(arr => {
// 这时候返回的是一个数组
console.log(arr);
}, ex => {
console.error(ex);
});
输出:
这个简单过一下,和Python没有太多不一样
用function*
来定义一个迭代器
function* show() {
console.log("a");
yield "1";
console.log("b");
yield "2";
console.log("c");
return "d";
}
let gen = show();
// 每一次next都执行到下一个yield中止
console.log(gen.next());
// 返回值.value 能够获得yield返回的值
console.log(gen.next().value);
// done==true的时候表明迭代结束
console.log(gen.next());
输出:
a {value: "1", done: false} b 2 c {value: "d", done: true}
经过上面输出能够瞬间知道退出条件:done: true
,那么遍历方式就来了:
function* show() {
yield "1";
yield "2";
return "d";
}
let gen = show();
while (true) {
let result = gen.next();
if (result.done) {
console.log(`返回值:${result.value}`);
break;
} else {
console.log(result.value);
}
}
输出:
1 2 返回值:d
JS也提供了for of
来遍历:
for (let item of show()) {
console.log(item);
}
大致上差很少,结束条件是触发StopIteration
异常
def show():
yield "1"
yield "2"
return "d"
gen = show()
while True:
try:
print(next(gen))
except StopIteration as ex:
print(f"返回值:{ex.value}")
break
for item in show():
print(item) # 1 2
输出:
1 2 返回值:d 1 2
function* show2() {
a = yield "111";
console.log(a);
b = yield a;
console.log(b);
c = yield b;
console.log(c);
return "over";
}
let gen = show2();
// 和Python同样,第一个不传参
console.log(gen.next());
console.log(gen.next("aaa"));
console.log(gen.next("bbb"));
console.log(gen.next("ccc"));
输出:
{value: "111", done: false} aaa {value: "aaa", done: false} bbb {value: "bbb", done: false} ccc {value: "over", done: true}
传参Python是使用的send方法,其实next本质也是send,这个以前讲过了:
def show():
a = yield "111"
print(a)
b = yield a
print(b)
c = yield b
print(c)
return "over"
gen = show()
# 第一个不传参
print(next(gen)) # gen.send(None)
print(gen.send("aaa"))
print(gen.send("bbb"))
try:
print(gen.send("ccc"))
except StopIteration as ex:
print(ex.value)
输出:
111 aaa bbb bbb ccc over
async/await
¶若是你如今尚未用过async
和await
的话...须要好好提高下了,仍是通俗说下吧:
ES6出来前,咱们用异步通常是这么用的:
<script src="./js/test.js" async></script>
如今能够正经的使用了,继续把上面那个例子衍生下:(以前用then(()=>{},()=>{})
,如今可使用async
和await
来简化)
async function show(url) {
let data = await $.ajax({ url: url, dataType: 'json' });
console.log(data)
}
show("./data/list.txt")
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
就算是批量任务也不用那么麻烦了:
let show = async (urls) => {
for (const url of urls) {
let data = await $.ajax({ url: url, dataType: "json" });
console.log(data);
}
}
show(["./data/user.json", "./data/list.txt", "./data/package.json"]);
输出:
{Name: "小明", Age: 23} [1, 2, 3, 4, 5, 6, 7, 8, 9] {name: "data", version: "0.1.0", description: "测试", main: "index.js", scripts: {…}, …}
应用常见其实不少,好比执行某个事件、好比引入某个外部JS...,eg:
test.js
(async () => {
let data = await $.ajax({ url: "./data/list.txt", dataType: 'json' });
console.log(data);
})();
HTML中引用一下:<script src="./js/test.js" async></script>
输出:
[1, 2, 3, 4, 5, 6, 7, 8, 9]
和NetCore
同样,能够嵌套使用的,await
的对象通常都是Promise
或者同是async
修饰的方法
举个例子:
test.js
:
let show = async (urls) => {
for (const url of urls) {
let data = await $.ajax({ url: url, dataType: "json" });
console.log(data);
}
return "ok";
}
let test = async () => {
let result = await show(["./data/user.json", "./data/list.txt", "./data/package.json"]);
return result;
}
页面
<script src="./js/test.js"></script>
<script>
(async () => {
let data = await test();
console.log(data);
})();
</script>
输出:
{Name: "小明", Age: 23} [1, 2, 3, 4, 5, 6, 7, 8, 9] {name: "data", version: "0.1.0", description: "测试", main: "index.js", scripts: {…}, …} ok
Python3.7开始,语法才开始简洁:
import asyncio
# 模拟一个异步操做
async def show():
await asyncio.sleep(1)
return "写完文章早点睡觉哈~"
# 定义一个异步方法
async def test(msg):
print(msg)
return await show()
# Python >= 3.7
result = asyncio.run(test("这是一个测试"))
print(result)
# Python >= 3.4
loop = asyncio.get_event_loop()
result = loop.run_until_complete(test("这是一个测试"))
print(result)
loop.close()
输出:
这是一个测试 写完文章早点睡觉哈~
这个ES6里面有,可是浏览器并无彻底支持,因此如今你们仍是用Require.js
和Sea.js
更多点
简单看看就行:扩展连接 ~ https://www.cnblogs.com/diligenceday/p/5503777.html
模块定义:
export { a, test, user }
let test = () => {
console.log("test");
}
let user = () => {
console.log("user");
return "小明";
}
let a = 1;
导入模块:
import { a, test, user } from "./mod.js"
console.log(a);
test();
console.log(user());