Class 的基本语法
JavaScript 语言中,生成实例对象的传统方法是通过构造函数。下面是一个例子。
1. function Point(x, y) { 2. this.x = x; 3. this.y = y; 4. } 5. 6. Point.prototype.toString = function () { 7. return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘; 8. }; 9. 10. var p = new Point(1, 2);
上面的代码用 ES6的 class 改写
1. class Point { 2. constructor(x, y) { 3. this.x = x; 4. this.y = y; 5. } 6. 7. toString() { 8. return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘; 9. } 10. }
使用的时候,也是直接对类使用 new 命令,跟构造函数的用法完全一致。
1. class Bar { 2. doStuff() { 3. console.log(‘stuff‘); 4. } 5. } 6. 7. var b = new Bar(); 8. b.doStuff() // "stuff"
在类的实例上面调用方法,其实就是调用原型上的方法。
1. class B {} 2. let b = new B(); 3. 4. b.constructor === B.prototype.constructor // true
类的实例
生成类的实例的写法,与 ES5 完全一样,也是使用 new 命令。前面说过,如果忘记加上 new ,
像函数那样调用 Class ,将会报错。
1. class Point { 2. // ... 3. } 4. 5. // 报错 6. var point = Point(2, 3); 7. 8. // 正确 9. var point = new Point(2, 3);
与 ES5 一样,实例的属性除非显式定义在其本身(即定义在 this 对象上),否则都是定义在原型
上(即定义在 class 上)。
1. //定义类 2. class Point { 3. 4. constructor(x, y) { 5. this.x = x; 6. this.y = y; 7. } 8. 9. toString() { 10. return ‘(‘ + this.x + ‘, ‘ + this.y + ‘)‘; 11. } 12. 13. } 14. 15. var point = new Point(2, 3); 16. 17. point.toString() // (2, 3) 18. 19. point.hasOwnProperty(‘x‘) // true 20. point.hasOwnProperty(‘y‘) // true 21. point.hasOwnProperty(‘toString‘) // false 22. point.__proto__.hasOwnProperty(‘toString‘) // true
上面代码中, x 和 y 都是实例对象 point 自身的属性(因为定义在 this 变量上),所
以 hasOwnProperty 方法返回 true ,而 toString 是原型对象的属性(因为定义在 Point 类
上),所以 hasOwnProperty 方法返回 false 。这些都与 ES5 的行为保持一致。
1. var p1 = new Point(2,3); 2. var p2 = new Point(3,2); 3. 4. p1.__proto__ === p2.__proto__ 5. //true
取值函数(getter)和存值函数(setter)
与 ES5 一样,在“类”的内部可以使用 get 和 set 关键字,对某个属性设置存值函数和取值函
数,拦截该属性的存取行为。
1. class MyClass { 2. constructor() { 3. // ... 4. } 5. get prop() { 6. return ‘getter‘; 7. } 8. set prop(value) { 9. console.log(‘setter: ‘+value); 10. } 11. } 12. 13. let inst = new MyClass(); 14. 15. inst.prop = 123; 16. // setter: 123 17. 18. inst.prop 19. // ‘getter‘
prop 属性有对应的存值函数和取值函数,因此赋值和读取行为都被自定义了。
属性表达式
类的属性名,可以采用表达式。
1. let methodName = ‘getArea‘; 2. 3. class Square { 4. constructor(length) { 5. // ... 6. } 7. 8. [methodName]() { 9. // ... 10. } 11. }
上面代码中, Square 类的方法名 getArea ,是从表达式得到的。
Class 表达式
与函数一样,类也可以使用表达式的形式定义。
1. const MyClass = class Me { 2. getClassName() { 3. return Me.name; 4. } 5. };
上面代码使用表达式定义了一个类。需要注意的是,这个类的名字是 Me ,但是 Me 只在 Class
的内部可用,指代当前类。在 Class 外部,这个类只能用 MyClass 引用。
1. let inst = new MyClass(); 2. inst.getClassName() // Me 3. Me.name // ReferenceError: Me is not defined
上面代码表示, Me 只在 Class 内部有定义。
2021-05-24 17:37:16
2020.05.24(Class 的基本语法、类的实例、取值函数(getter)和存值函数(setter)、属性表达式、Class 表达式)
原文:https://www.cnblogs.com/zhenggc99/p/14805414.html