剖析ES类的constructor及static,public,private,protected区别

ES6引入了class类的概念,创建的每一个class类,都会有一个constructor()方法,该方法是一种用于创建和初始化class创建的对象的特殊方法–构造函数方法。

class Animal(){}
等同于
class Animal(){
    constructor(){}  //默认的constructor方法
}

继承

class Parent {
		constructor(name, age) {
				this.name = name;
				this.age = age;
		}
		getName() {
				console.log(this.name)
		}
}
class Child extends Parent {
		constructor(name, age) {
				super(name, age) //代表父类的构造函数
				this.name = name // super 之前会报错, 应该写在super 之后
		}
}

拓展,添加protected声明的变量可以直接访问

class Parent {
    constructor(protected name) {

    }
    getName() {
            console.log(this.name)
    }
}

在ES6中,我们的javascript也有了类,那么,JS中的类有没有static,public,private,protected这些关键字呢,又是怎么样的呢,本文主要带你探讨JS类中的static,public,private,protected这些关键字的使用。

1、static

类(class)通过 static 关键字定义静态方法。不能在类的实例上调用静态方法,而应该通过类本身调用。这些通常是实用程序方法,例如创建或克隆对象的功能。

静态方法调用同一个类中的其他静态方法,可使用this关键字。

class StaticMethodCall {
    static staticMethod() {
        return 'Static method has been called';
    }
    static anotherStaticMethod() {
        return this.staticMethod() + ' from another static method';
    }
}
StaticMethodCall.staticMethod();
// 'Static method has been called'
 
StaticMethodCall.anotherStaticMethod();
// 'Static method has been called from another static method'


非静态方法中,不能直接使用 this关键字来访问静态方法。而是要用类名来调用:CLASSNAME.STATIC_METHOD_NAME() ,或者用构造函数的属性来调用该方法: this.constructor.STATIC_METHOD_NAME().

class StaticMethodCall {
    constructor() {
        console.log(StaticMethodCall.staticMethod());
        // 'static method has been called.'
        console.log(this.constructor.staticMethod());
        // 'static method has been called.'
    }
    static staticMethod() {
        return 'static method has been called.';
    }
}


2、public

public是默认的访问控制符,不给属性和方法写访问控制符时,默认是public。
添加了public的属性和方法可以在类的内部和类的外部被访问到。

class Person {
    public name; 
    public eat() {  
        console.log('i am eating');
        console.log(name);  // public修饰的属性在类的内部被访问到
    }
} 

var p1 = new Person();  
p1.name = 'zhagnsan';  // public修饰的属性在类的外部被访问到
p1.eat();  // public修饰的方法在类的外部被访问到


3、private

添加了private的属性和方法只能可以在类的内部被访问到,如果在类的外部访问就会报错

class Person {
    private name; 
    private eat() {  
        console.log('i am eating');
        console.log(name); // private修饰的属性只能在类的内部被访问到
    }
} 

4、protecred

添加了protecred的属性和方法只能可以在类的内部和子类被访问到。

class Person {
    protected name; 

    protected eat() {  
        console.log('i am eating');
        console.log(name); // protected修饰的属性在类的内部被访问到
    }
} 

class Staff extends Person{
    public doWork() {
        this.eat(); // protected修饰的属性在子类被访问到
        console.log('i am working');
    }
}

var staff1 = new Staff();
staff1.doWork();
  • 2
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值