闭包、访问器属性、类与对象的创建与成员引用、数组与对象的解构
发布于:2022-01-25 09:15:26
次阅读
闭包
// 闭包:// 1、父子函数// 2、子函数调用了父函数中的变量let fn = function (a) { let f = function (b) { return a + b; }; // 返回子函数 return f;};// fn()调用完成,但是内部的a被子函数引用了, 所以fn()创建的作用域不消失let aa = fn(1);console.log(aa(2));// 偏函数:// 当一个函数需要传入多个参数时,不一定要一次性都传入,可分批传入fn = function (a, b) { return function (c) { return a + b + c; };};let cc = fn(1, 2);console.log(cc(3));// 将参数逐个传入,叫“柯里化”函数fn = function (a) { return function (b) { return function (c) { return a + b + c; }; };};console.log(fn(1)(2)(3));// 以上也可以用箭头函数简写fn = (a) => (b) => (c) => a + b + c;console.log(fn(1)(2)(3));
访问器属性
// 访问器属性let score = { data: { math: 90, english: 80 }, get math() { return this.data.math; }, set math(math) { if (math <= 100 && math >= 0) { this.data.math = math; } else { console.log("成绩错误"); } }, get score() { return `math:${this.data.math} , english:${this.data.english}`; },};console.log(score.math);score.math = 100;console.log(score.score);score.math = 1000;
类与对象的创建与成员引用
// 类的创建// 构造函数 旧的写法let Score = function (math, english) { this.math = math; this.english = english;};// 对象方法一般是公共, 操作的是当前对象的属性// 任何一个函数都有一个属性 prototype, 叫原型, 这个原型,对于普通函数来说,没用// 只有把函数当 成构造函数来创建对象时, 这个原型属性才有用// 给类 Score 添加自定义方法,必须添加到它的原型对象属性上// 声明在 Score.prototype 原型上的方法, 被所有类实例/对象所共用Score.prototype.score = function () { return `math:${this.math} english:${this.english}`;};s = new Score(80, 90);console.log(s.score());// 静态成员: 直接挂载到构造函数对象上的属性Score.num = 2;console.log(Score.num);Score = function (math, english, num) { this.math = math; this.english = english; // 私有成员,本构造函数外,无法访问 let number = num; console.log(number);};Score.prototype.score = function () { // ${this.number} 无法访问 return `math:${this.math} english:${this.english} num:${this.number}`;};s = new Score(90, 80, 2);console.log(s.score());// ES6 写法class S { // 公共字段(可选) math = 0; english = 0; //私有成员 #number = 0; //构造函数 constructor(math, english, num) { this.math = math; this.english = english; this.#number = num; } //公共方法 getScore() { return `math:${this.math} english:${this.english} num:${this.#number}`; } //静态成员 static flag = 1;}ss = new S(30, 20, 6);console.log(ss.getScore());class PS extends S { constructor(math, english, num, pe) { super(math, english, num); this.pe = pe; } getScore() { return `${super.getScore()} pe:${this.pe}`; }}p = new PS(20, 30, 4, 50);console.log(p.getScore());console.log(PS.flag);
数组与对象的解构
// 解构赋值let [math, english] = [40, 50];console.log(math, english);// 参数不足 ,用默认值[math, english, pe = 30] = [40, 50];console.log(math, english, pe);// 参数过多[math, english, ...ex] = [23, 45, 75, 45, 23, 86];console.log(ex);// 解构对象// 对象模板 = 对象字面量let {m,e}= { m: 24, e: 40 };console.log(m);// 大括号 不能出现在等号左边, {}不能充当"左值", 使用括号包一下转为表达式就可以了 ({ math, english }) = { math: 20, english: 40 };console.log(math);// 当左边模板中的变量出现命名冲突,使用别名解决let {math:ma,english:exx}= { math: 20, english: 40 };console.log(exx);// 实例// 用对象解构传参function getScore({math,english}){console.log(math,english);}getScore({math:30,english:40});