Class
JavaScript 中,类是一种函数
1 2 3 4 5 6 7
| class User { constructor(name) { this.name = name; } sayHi() { alert(this.name); } }
alert(typeof User);
|
class User {...}
构造实际上做了如下的事儿:
- 创建一个名为
User
的函数,该函数成为类声明的结果。该函数的代码来自于
constructor
方法(如果我们不编写这种方法,那么它就被假定为空)。
- 存储类中的方法,例如
User.prototype
中的
sayHi
。
类表达式
1 2 3 4 5
| let User = class { sayHi() { alert("Hello"); } };
|
类似于命名函数表达式(Named Function
Expressions),类表达式可能也应该有一个名字。
如果类表达式有名字,那么该名字仅在类内部可见。
类字段
“类字段”是一种允许添加任何属性的语法。
1 2 3 4 5 6 7 8 9
| class User { name = "John";
sayHi() { alert(`Hello, ${this.name}!`); } }
new User().sayHi();
|
类字段重要的不同之处在于,它们会在每个独立对象中被设好,而不是设在
User.prototype
:
即类字段只在实例化时进行。
类继承
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
| class Animal {
constructor(name) { this.speed = 0; this.name = name; }
run(speed) { this.speed = speed; alert(`${this.name} runs with speed ${this.speed}.`); }
stop() { this.speed = 0; alert(`${this.name} stands still.`); }
}
class Rabbit extends Animal { hide() { alert(`${this.name} hides!`); }
stop() { super.stop(); this.hide(); } }
let rabbit = new Rabbit("White Rabbit");
rabbit.run(5); rabbit.stop();
|
静态属性和静态方法
静态方法:属于类本身的方法。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| class Article { constructor(title, date) { this.title = title; this.date = date; }
static compare(articleA, articleB) { return articleA.date - articleB.date; } }
let articles = [ new Article("HTML", new Date(2019, 1, 1)), new Article("CSS", new Date(2019, 0, 1)), new Article("JavaScript", new Date(2019, 11, 1)) ];
articles.sort(Article.compare);
alert( articles[0].title );
|
静态属性
1 2 3 4 5
| class Article { static publisher = "Levi Ding"; }
alert( Article.publisher );
|
静态方法和属性只能通过类名调用,而不能通过对象实例。
静态方法和属性都可以继承。
私有属性与方法
- 受保护的字段以
_
开头。这是一个众所周知的约定,不是在语言级别强制执行的。程序员应该只通过它的类和从它继承的类中访问以
_
开头的字段。
- 私有字段以
#
开头。JavaScript
确保我们只能从类的内部访问它们。
类检查
instanceof
1 2 3 4 5 6 7 8 9 10 11 12
| class Rabbit {} let rabbit = new Rabbit();
alert( rabbit instanceof Rabbit );
function Rabbit() {} alert( new Rabbit() instanceof Rabbit );
let arr = [1, 2, 3]; alert( arr instanceof Array ); alert( arr instanceof Object );
|
让我们总结一下我们知道的类型检查方法:
|
用于 |
返回值 |
typeof |
原始数据类型 |
string |
{}.toString |
原始数据类型,内建对象,包含
Symbol.toStringTag 属性的对象 |
string |
instanceof |
对象 |
true/false |