类
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);