1

[JS] 类 class入门使用

 2 years ago
source link: https://segmentfault.com/a/1190000040923486
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[JS] 类 class入门使用

发布于 11 月 7 日

class是用于创建对象的模板。
(在js中构造函数也能批量创建对象,要注意函数有声明提升,而类没有声明提升,必须先定义类,在创建类的实例)

定义Animal类。类也是一个函数。

typeof(Animal) // function

对一个类本身来说,要注意以下四点:
1、构造函数constructor,这个函数用户在创建实例的时候传入参数。(new Animal("Jerry", 5))
2、方法,构造函数内部定义方法不需要function关键字。
3、setter、getter。setter和getter都是有特殊功能的属性,定义的时候分别使用set 关键字和get 关键字来定义,这二者定义的形式很像函数,但它们的用法都是属性的用法(object.key = value)
4、静态方法,在一个静态方法里调用另一个静态方法可以使用this,这里的this不绑定实例,而是绑定类本身;静态方法要用类调用,而不能用实例调用。

子类 (使用 extends 创建子类)

要注意:
1、子类的constructor函数中如果需要使用this,必须先执行super()方法初始化this。super初始化的参数应与父类constructor的参数相同,这样创建子类实例的时候才能对应上。
2、子类中与父类的同名方法是覆盖关系,即子类方法覆盖父类方法。
3、子类与父类同名getter和setter是覆盖关系。
4、子类与父类的同名静态方法也是覆盖关系。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK