闭包(1.父子函数 2.子函数调用了父函数中的变量)
function f2(){
let a = 1;
return function (){
retrun (a = a + 1);
}
}
const f = f2();
console.log(f());//1
console.log(f());//2
//分批传入参数
fn = function(a){
return function(b){
return function(c){
return a + b + c;
}
}
}
//箭头函数简写
fn = a => b => c => a+b+c;
console.log(fn(1)(2)(3));
//或者
f = fn(1);
f2 = fn(2);
console.log(f2(3));
let discound = 0.8;
function getPrice(price, discound = 1) {
// 纯函数中禁用有自由变量
return price * discound;
}
console.log(getPrice(12000, discound));
访问器属性
let user = {
data:{name:"nn",email:"email"},
// 访问email [注意空格必须]
get email(){
return user.data.email;
},
// 设置email [注意空格必须]
set email(email){
this.data.email = email;
}
};
user.email = "mm";
console.log(user.email)
类与构造函数
//首字母必须大写
let User = function(name,email,sex){
//私有成员
let gender = sex;
this.name = name;
this.email = email;
}
//调用
const user1 = new User("admin","email","male");
//给User添加方法
User.prototype.getInfo = function(){
retrun `name = ${this.name},email = ${this.email}`;
}
console.log(user1.getInfo);
//静态成员直接挂载到对象上的属性
User.status = "enabled";
console.log(User.status);
class User1{
//公共字段(可选)
name = 'username';
email = 'email.com';
//私有成员
#gender = 'male';
//构造方法
constructor(name,enmail,sex){
this.name = name;
this.email = email;
this.#gender = sex;
}
//公共方法:原型
getInfo(){
return `name = ${this.name},email = ${this.email}`;
}
//静态成员
static status = "enabled";
}
//调用
const user4 = new User1("name","email","sex");
//继承
class Child extends User1{
constructor(name,email,sex,salary){
//调用父级构造函数
super(name,email,sex);
//子类新属性
this.salary = salary;
}
//重写父类方法
getInfo(){
//调用父类方法
return `${super.getInfo()},salary = ${this.salary}`;
}
}
//调用
const user5 = new User1("name2","email2","sex2","123456");
//在类中使用访问器属性(访问与修改私有成员)
class Stu{
#age = 0;
get age(){
return this.#age;
}
set age(age){
this.age = age;
}
}
//调用
let stu = new Stu();
//设置
stu.age = 100;
//访问
stu.age
解构赋值
//age 默认值
let [name,email,age = 10] = ["nn","ee"];
console.log(name,email);
//对象模板必须等于对象字面量
let {id,lesson,score} = {id:1,lesson:'js',score:80}
//再次赋值必须加括号包含
({id,lesson,score}) = {id:2,lesson:'js2',score:22}
//别名(命名冲突时使用)
let {id:userId,lesson:userLesson,score:userScore} = {id:2,lesson:'js2',score:22}
console.log(userId);
//克隆对象
let {...obj} = {id:1,lesson:'js',score:80}
//案例
function getUser({id,name,email}){
//解构传参
console.log(id,name,email);
}
getUser({id:123,name:'name','email'})