Skip to content

实例属性 ​

本节目标:理解“实例属性”的核心思路,并能把它用于实际开发或面试表达。

**实例的属性需定义在****this****对象上,否则都是定义在原型上(即定义在****class****上)。**
//定义类
class Point {
    constructor(x, y) {
        this.x = x;
        this.y = y;
    }
    toString() {
        return '(' + this.x + ', ' + this.y + ')';
    }
}
var point = new Point(2, 3);
point.toString() // (2, 3)
point.hasOwnProperty('x') // true
point.hasOwnProperty('y') // true
point.hasOwnProperty('toString') // false
point.__proto__.hasOwnProperty('toString') // true
**实例属性的新写法**
实例属性可以定义在类的最顶层,构造函数之外,这时不需要在实例属性前面加上this。如:
class IncreasingCounter {
    _count = 0;
    get value() {
        console.log('Getting the current value!');
        return this._count;
    }
    increment() {
        this._count++;
    }
}
新写法的好处:
所有实例对象自身的属性都定义在类的头部,实例的属性一目了然。
class foo {  bar = 'hello';  baz = 'world';
constructor() {    // ...  }}

本站总访问 — 次