标签:private div ... rip 注意 field error: 对象 console
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
toString() {
return ‘(‘ + this.x + "," + this.y + ")";
}
toValue() {
return this.x + this.y;
}
}
Symbol值的唯一性,将私有方法的名字命名为一个Symbol值。const bar = Symbol(‘bar‘);
const snaf = Symbol(‘snaf‘);
export default class myClass{
// 公有方法
foo(baz) {
this[bar](baz);
}
// 私有方法
[bar](baz) {
return this[snaf] = baz;
}
// ...
};
class Point { #x; constructor(x = 0) { #x = +x; // 写成 this.#x 亦可 } get x() { return #x } set x(value) { #x = +value }}
}
static关键字,就表示该方法不会被实例继承,而是直接通过类来调用,这就称为“静态方法”。class Foo { static classMethod() { return ‘hello‘; }} Foo.classMethod() // ‘hello‘ var foo = new Foo(); foo.classMethod() // TypeError: foo.classMethod is not a function
class Foo { static classMethod() { return ‘hello‘; }} class Bar extends Foo {} Bar.classMethod() // ‘hello‘
super对象上调用的。class Foo {
static classMethod() {
return ‘hello‘;
}}
class Bar extends Foo {
static classMethod() {
return super.classMethod() + ‘, too‘;
}}
Bar.classMethod() // "hello, too"
Class.propName。class MyClass { myProp = 42; constructor() { console.log(this.myProp); // 42 }}
static关键字就可以了class MyClass { static myStaticProp = 42; constructor() { console.log(MyClass.myStaticProp); // 42 }}
this,它默认指向类的实例。但是,必须非常小心,一旦单独使用该方法,很可能报错。class Logger {
printName(name = ‘there‘) {
this.print(`Hello ${name}`);
}
print(text) {
console.log(text);
}}
const logger = new Logger();
const { printName } = logger;printName(); // TypeError: Cannot read property ‘print‘ of undefined
this,这样就不会找不到print方法了。class Logger {
constructor() {
this.printName = this.printName.bind(this);
}
// ...
}
-- 使用箭头函数
class Logger {
constructor() {
this.printName = (name = ‘there‘) => {
this.print(`Hello ${name}`);
};
}
// ...
}
标签:private div ... rip 注意 field error: 对象 console
原文地址:http://www.cnblogs.com/nankeyimeng/p/7197825.html