javaScript之类、继承、合并空运算符(ES5、ES6、ES2020静态属性、私有属性、继承)

ES5中的类

构造函数模拟类的概念

 function Person(name){
    this.name = name;
    this.age = 20;
}
Person.prototype.fn = function(){
    console.log("fn...");
}
// es5 静态属性;
Person.num = 10;
let zhangsan = new Person("张三");
console.log(zhangsan);
zhangsan.fn();
console.log(Person.num);  //10

ES6中的类

class Person{
    height="178cm";
    static num = 10;    //静态属性;
    constructor(name){
        this.name = name;
        this.age = 20;
    }
    fn(){
        console.log("fn...");
    }
}
let zhangsan = new Person("张三");
console.log(zhangsan);
console.log(zhangsan.name,zhangsan.age,zhangsan.height);
zhangsan.fn();
console.log(Person.num);  //10

ES2020中的类

class Person{
    #age = 25;   //私有属性;(类内部调用)
    constructor(myname){
        // var _age = 26;  //模拟私有属性;
        this.myname = myname;
        this.height= "178cm";
    }
    // getAge 共有方法 调取私有属性;
    getAge(){
        return this.#age;
    }
}
let zhangsan = new Person("张三");
//console.log(zhangsan.#age); //读取不到类,报错
console.log(zhangsan.getAge());

继承

ES5继承

function Dad(height){
    this.name = "张安";
    this.age =50;
    this.height = height;
}
function Son(height){
    Dad.call(this,height)
}
let newSon = new Son("178cm");
console.log(newSon);

ES6继承

class Dad {
    static num = 10;
    constructor(height) {
        this.name = "张安";
        this.age = 50;
        this.height = height;
    }
    fn(){
        console.log("Dad fn")
    }
}
class Son extends Dad{
    constructor(height){
        super(height);  //必须在前边
        this.hobby = "篮球";
    }
    fn(){
        super.fn();  //执行父类fn方法;
        console.log("Son fn")
    }
}
console.log(Son.num);
let newSon = new Son("178cm");
console.log(newSon);
newSon.fn();  //Dad fn    Son fn

ES2020合并空运算符

在ES2020之前,在函数中设置了默认参数,给传空字符串时就会报错。ES6给出了 “??” 来合并空运算符。

function test(name,age){
     name = name ?? "张三";
     age = age ?? 20;
     console.log(name,age);
}
test();   // 张三  20
test("",0);  //不会报错
  let str = 0;
  let res = str || 1;
  console.log(res);   // 1;  或运算
  
  let str = 0;
  let res = str ?? 1; 
  console.log(res);  // 0;  相当于与运算
  • 可选链式操作;ES2020;
let obj = {};
console.log(obj.person?.name);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值