class语法

10次阅读

共计 1388 个字符,预计需要花费 4 分钟才能阅读完成。

Class 语法

1:类的定义
class Point {
m; // 也可以定义在顶部
constructor(x, y) {

// 定义类的属性可以在  constructor 函数当中使用 this
this.x = x;
this.y = y;

}

toString() {

return '(' + this.x + ',' + this.y + ')';

}
}

注意:定义类的方法的时候,前面不需要加 function 关键字,方法之间也不需要加逗号分隔

2:类的数据类型是函数,类本身指向构造函数
使用的时候,也是直接对类使用 new 命令,类的所有方法都定义在类的 prototype 属性上面

3:一次性添加多个方法
class Point {
constructor(){

// ...

}
}

Object.assign(Point.prototype, {
toString(){},
toValue(){}
});

注意:类的内部定义的方法,都是不可枚举的

4:取值函数(getter)和存值函数(setter)
在“类”的内部可以使用 get 和 set 关键字,对某个属性设置存值函数和取值函数,拦截该属性的存取行为
class MyClass {
constructor() {

// ...

}
get prop() {

return 'getter';

}
set prop(value) {

console.log('setter:'+value);

}
}

let inst = new MyClass();

inst.prop = 123;
// setter: 123

inst.prop
// ‘getter’

5:类的属性名可以采用表达式
let methodName = ‘getArea’;

class Square {
constructor(length) {

// ...

}

[methodName]() {

// ...

}
}

6:类也可以采用表达式的形式定义
const MyClass = class Me {
getClassName() {

return Me.name;

}
};

注意:需要注意的是,这个类的名字是 Me,但是 Me 只在 Class 的内部可用,指代当前类。在 Class 外部,这个类只能用 MyClass 引用

7:注意点
{

1:类的内部默认使用严格模式
2:类不存在变量提升
3:ES6 的类只是 ES5 的构造函数的包装,所以函数的许多特性都会被继承,包括 name 属性
4:如果某个方法之前加上星号(*),就表示该方法是一个 Generator 函数
5:类的方法内部如果含有 this,它默认指向类的实例

}

8:静态方法
类相当于实例的原型,所有在类中定义的方法,都会被实例继承。
如果在一个方法前,加上 static 关键字,就表示该方法不会被实例继承,
而是直接通过类来调用,这就称为“静态方法”。

静态方法当中的 this 指向类,而不是实例

class Foo {
static classMethod() {

return 'hello';

}
}

Foo.classMethod() // ‘hello’

var foo = new Foo();
foo.classMethod()
// TypeError: foo.classMethod is not a function

9:静态属性
class Foo {
}

Foo.prop = 1;
Foo.prop // 1

这个属性实例不会继承
目前,只有 这种写法可行,因为 ES6 明确规定,Class 内部只有静态方法,没有静态属性

提案:写法是在实例属性的前面,加上 static 关键字

10:私有方法和属性
待续 …

正文完
 0