使用 symbol唯一性 + 块级作用域
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21var class1; { let x=Symbol('qwdw'); let y='xx1'; class1 = class Txx1{ constructor(){ console.log('const'); this[x](); console.log('const2'); } [x](){ console.log('start'); console.log(this); console.log('end'); } [y](){ console.log(this); } } }
使用属性特性 + 返回错误提示
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18class T { y=1; constructor(){ Object.defineProperty(this,'y',{ enumerable:false, writable:false, value:0 }); } x(){ if(this.y && new.target){ //..... }else{ throw Error('私有方法'); } } }
闭包
复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13class T{ constructor(){ function x(){ console.log('哈哈') } return new class{ constructor(){ x(); } } } }
最后
以上就是高贵硬币最近收集整理的关于3种方式 - 真实实现class 私有方法的全部内容,更多相关3种方式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复