在JavaScript中我们如何实现class类的属性的访问限制呢?详解static,public,protected,private

在JavaScript中我们如何实现class类的属性的访问限制呢?

static

JavaScript中,static关键字是用来定义静态属性或静态方法的;
它使得可以通过类本身全局操作一些变量和方法

	//  示例代码
    class Prent {
    
    
        static age = 99;
        // 静态方法
        static getAge() {
    
    
            console.log(this.age);
        }
    }
    Prent.getAge();
    console.log(Prent.age)

public

如何设置一个公共属性,使得类的内部和外部还有继承的子类都可以进行访问呢?
很简单,平常在类中设置的就是公共属性

    // 示例代码
    class Prent {
    
    
        constructor(name) {
    
    
            // 公共属性
            this.name = name || 'xiao';
        }
        // 公共方法
        getName() {
    
    
        	//  内部访问
            console.log(this.name)
        }
    }
    const p = new Prent();
    //  外部访问
    p.getName();
    console.log(p.name)
    class Son extends Prent {
    
    
    }
    const s = new Son();
    //  子类访问
    s.getName();
    console.log(s.name)

protected

建立一个类,对其内部属性进行保护,使得外部不可访问,只有当前类和其子类可以访问
通过getter,setter来访问和设置其内部属性

    // 内部对属性进行保护,使外部不能进行访问
    // 方式一
    const HOST = Symbol("host")
    // 方式二
    const HOSTWEAKMAP = new WeakMap();
    
    class Prent {
    
    
        constructor() {
    
    
            // 属性保护,只能当前类和子类能够访问
            this[HOST] = 'www.baidu.com';
            HOSTWEAKMAP.set(this, 'www.qq.com');
        }
        get host() {
    
    
            return this[HOST]
        }
        get hostweak() {
    
    
            return HOSTWEAKMAP.get(this);
        }
    }
    const p = new Prent();
    console.log(p.host)
    console.log(p.hostweak)
    
    class Son extends Prent {
    
    
    }
    const s = new Son();
    console.log(s.host)
    console.log(s.hostweak)

private

在一个类内部建立私有属性只能内部自己使用,外部和子类都不能进行访问
我们可以使用 # 来声明私有属性

    class Prent {
    
    
        // 私有属性
        #name = "456xxx";
        // 私有方法
        #getName() {
    
    
            console.log(this.#name)
        }
        // 公共方法
        getName() {
    
    
            this.#getName();
        }
    }
    const p = new Prent();
    p.getName();
    // 访问将会报错 Property '#getName' is not accessible outside class 'Prent' because it has a private identifier.
    // p.#getName();
    class Son extends Prent {
    
    
    }
    const s = new Son();
    // 子类只能通过父类暴露公共方法来访问其内部私有属性
    s.getName();

猜你喜欢

转载自blog.csdn.net/xiaorunye/article/details/129867935
今日推荐