如何防止es6中的函数覆盖?

时间:2017-08-08 03:44:37

标签: javascript ecmascript-6

这是我通常用来阻止覆盖name属性的方法。



let _name = Symbol('name');

class Cat {
    constructor(name) {
        this[_name] = name;
    }
    set name(newName) {
        return this[_name];
    }
    get name() {
    	return this[_name];
    }
}

// default name
let cat = new Cat('Hermione');

// new name
cat.name = 'Voldermort';

// testing
console.log(cat.name);




我的想法:将name属性的值保存到另一个变量。

但是如果我有多个类属性,就像这样:

1

浪费时会浪费很多钱来保存。

let _Min = Symbol('Min'), _Max = Symbol('Max'); // and so on

还有其他方法可以实现这一目标吗?谢谢!

2 个答案:

答案 0 :(得分:2)

为了是只读的,该属性应该没有set访问者:

class Foo {
  get bar() {
    return 'bar';
  }
}

如果应该在构造时定义属性,则也可以定义描述符:

class Cat {
  constructor(name) {
    Object.defineProperty(this, name, {
      get: () => name,
      configurable: true
    });
  }
}

或者

class Cat {
  constructor(name) {
    Object.defineProperty(this, name, {
      value: name,
      writable: false,
      configurable: true
    });
  }
}

答案 1 :(得分:0)

尝试以下示例,可能会解决您的问题

示例1:

class A {
  a = () => {
    console.log('A#a');
  }
}

class B extends A {
  // this will throw error as
  // Class 'A' defines instance member property 'a', but extended class 'B' 
  // defines it as instance member function.
  a() {  
    console.log('B#a')
  }
}

new B().a()

/**
Error: Class 'A' defines instance member property 'a', but extended class 'B' 
defines it as instance member function.
*/

示例2:

class Renderer {
  constructor(args) {
    Object.defineProperty(this, 'render', {
      writable: false,
      configurable: true,
      value: () {
         return this.childRender();
      }
    });
  }

  childRender() {
    throw Error('render() is already instance of Renderer. Did you mean? childRender()');
  }

  // do not define methodName() here
}

class Draw extends Renderer {
  render() {
    console.log('DrawB#render');
  }
}

new Draw().render()
/**
VM1597:13 Uncaught Error: render() is already instance of Renderer. Did you mean? childRender()
    at Drawee.childRender (<anonymous>:13:11)
    at Drawee.value (<anonymous>:7:22)
    at <anonymous>:25:14
*/

我希望这对您有帮助