👧🏼 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😁😁😁
点赞 收藏 关注 谢谢大家。