使用 symbol唯一性 + 块级作用域
var 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);
}
}
}
使用属性特性 + 返回错误提示
class T {
y=1;
constructor(){
Object.defineProperty(this,'y',{
enumerable:false,
writable:false,
value:0
});
}
x(){
if(this.y && new.target){
//.....
}else{
throw Error('私有方法');
}
}
}
闭包
class T{
constructor(){
function x(){
console.log('哈哈')
}
return new class{
constructor(){
x();
}
}
}
}
最后
以上就是高贵硬币最近收集整理的关于3种方式 - 真实实现class 私有方法的全部内容,更多相关3种方式内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复