static
static
class User {
static staticMethod() {
alert(this === User);
}
}
User.staticMethod(); // true
class User { }
User.staticMethod = function() {
alert(this === User);
};
User.staticMethod(); // true
User.staticMethod() this User
Article
Article.compare
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 ); // CSS
Article.compare class
titledate
constructor
Article.createTodays()
class Article {
constructor(title, date) {
this.title = title;
this.date = date;
}
static createTodays() {
// this = Article
return new this("Today's digest", new Date());
}
}
let article = Article.createTodays();
alert( article.title ); // Today's digest
Article.createTodays() class
//
// Article
// id
Article.remove({id: 12345});
// ...
article.createTodays(); /// Error: article.createTodays is not a function
static
class Article {
static publisher = "Levi Ding";
}
alert( Article.publisher ); // Levi Ding
Article
Article.publisher = "Levi Ding";
Animal.compare Animal.planet Rabbit.compare Rabbit.planet
class Animal {
static planet = "Earth";
constructor(name, speed) {
this.speed = speed;
this.name = name;
}
run(speed = 0) {
this.speed += speed;
alert(`${this.name} runs with speed ${this.speed}.`);
}
static compare(animalA, animalB) {
return animalA.speed - animalB.speed;
}
}
// Animal
class Rabbit extends Animal {
hide() {
alert(`${this.name} hides!`);
}
}
let rabbits = [
new Rabbit("White Rabbit", 10),
new Rabbit("Black Rabbit", 5)
];
rabbits.sort(Rabbit.compare);
rabbits[0].run(); // Black Rabbit runs with speed 5.
alert(Rabbit.planet); // Earth
Rabbit.compare Animal.compare
extends Rabbit [[Prototype]] Animal
Rabbit extends Animal [[Prototype]]
RabbitAnimalRabbit.prototypeAnimal.prototype
class Animal {}
class Rabbit extends Animal {}
//
alert(Rabbit.__proto__ === Animal); // true
//
alert(Rabbit.prototype.__proto__ === Animal.prototype); // true
Article.compare(article1, article2) factory Article.createTodays()
static
class MyClass {
static property = ...;
static method() {
...
}
}
MyClass.property = ...
MyClass.method = ...
class B extends A B prototype AB.[[Prototype]] = A B A
<code><pre>10 plnkrJSBincodepen