【编程题与分析题】模拟实现私有变量
发布于 • 阅读量 907
模拟实现私有变量(面试加分项)
复制
class Example {
constructor(name){
this._private = name;
}
getName(){
return this._private;
}
}
let ex = new Example('private1');
console.log(ex.getName(), ex._private);
let ex1 = new Example('private2');
console.log(ex1.getName(), ex1._private);
class Example02 {
constructor(name){
let _private = '';
_private = name;
this.getName = function () {
return _private;
}
}
}
let ex01 = new Example02('private1');
console.log(ex01.getName(), ex01._private);
let ex02 = new Example02('private2');
console.log(ex02.getName(), ex02._private);
const Example03 = (function () {
let _private = '';
class Example03 {
constructor() {
_private = 'private';
}
getName(){
return _private;
}
}
return Example03;
})();
let ex3 = new Example03();
console.log(ex3.getName(), ex3._private)
const Example4 = (function () {
let _private = Symbol('private');
class Example4 {
constructor(props) {
this[_private] = 'private';
}
getName(){
return this[_private];
}
}
return Example4;
})();
const _private = new WeakMap();
class Example5 {
constructor(){
_private.set(this, 'private');
}
getName(){
return _private.get(this);
}
}
let ex5 = new Example5();
console.log(ex5.getName(), ex5.name)
const Example5 = (function () {
const _private = new WeakMap();
class Example5{
constructor(){
_private.set(this, 'private');
}
getName(){
return _private.get(this);
}
}
return Example5;
})();
class Point {
#x;
#y;
constructor(x, y){
this.#x = x;
this.#y = y;
}
equals(point){
return this.#x === point.#x && this.#y === point.#y;
}
}
评论