javascript中类的public,protected,private详解

本文介绍了JavaScript中类的public、protected和private三种访问修饰符。public属性在内部、外部和子类中都可访问;protected属性仅限内部和子类访问,可通过Symbol或weakMap实现;private属性仅限函数内部使用,可通过#声明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

👧🏼 START

在我们 javascript ES5 之前要想进行继承,封装,多态性,得使用到我们的原型,原型链来使用面向对象的过程,但是 ES6 之后新增了一个 class 语法,可以看做是 “语法糖”,实质还是运用了 ES5 的原型,和原型链进行实现的。


🎅🏼 01 - PUBLIC

我们定义一个类 User 设置公共属性(PUBLIC)

PUBLIC : 内部 和 外部 还有 子类 都可以进行访问的 属性 称为 公共属性。

class User {
	constructor(name,age) {
		this.name = name;
		this.age = age;
	}
}

外部访问:

class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}
let lisi = new User("李四", 13);
// 外部访问
console.log(lisi.name, lisi.age); // 李四 13

内部访问:

class User {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
    // 内部访问
    show() {
        return this.name;
    }
}
let lisi = new User("李四", 13);
console.log(lisi.show()); // 李四

🎅🏼 02 - PROTECTED

我们定义一个类 User 进行对属性保护

PROTECTED : 内部对属性进行保护,使外部不能进行访问。

第一种 使用 Symbol。


const HOST = Symbol("私有");
class User {
	constructor(url) {
		this[HOST] = url;
	}
	get host() {
		return this[HOST];
	}
}
let h = new User("http://www.baidu.com");
// 在外部是访问不到的。
console.log(h[Symbol()]); // undefined
console.log(h.host); // http://www.baidu.com

第二种 使用 weakMap。

const HOST = new WeakMap();
class User {

    constructor(url) {
        HOST.set(this, url);
    }

    get host() {
        return HOST.get(this);
    }
    
}

let h = new User("http://www.baidu.com");
console.log(h.host);

🎅🏼 03 - PRIVATE

PRIVATE 私有属性只能函数内部自己使用,外部和子类都不能进行访问。
可以使用 # 来声明 私有属性。

class User {

    #site = "xiaomi.com";
    constructor(url) {
        this.url = url;
    }
    #show = () => {
        return this.url;
    }
}

let h = new User("http://www.baidu.com");
console.log(h.#site); // Uncaught SyntaxError: Private field '#site' must be declared in an enclosing class
console.log(h.#show()); // Uncaught SyntaxError: Private field '#show' must be declared in an enclosing class

HAPPY😁😁😁



点赞 收藏 关注 谢谢大家。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值