Update article.md
This commit is contained in:
parent
1f9ae74ee4
commit
e842caf3cd
1 changed files with 9 additions and 9 deletions
|
@ -7,7 +7,7 @@ The "class" construct allows to define prototype-based classes with a clean, nic
|
|||
|
||||
## The "class" syntax
|
||||
|
||||
The `class` syntax is versatile, we'll start from a simple example first.
|
||||
The `class` syntax is versatile, we'll start with a simple example first.
|
||||
|
||||
Here's a prototype-based class `User`:
|
||||
|
||||
|
@ -57,13 +57,13 @@ Here's the code to dig into the class and see that:
|
|||
```js run
|
||||
class User {
|
||||
constructor(name) { this.name = name; }
|
||||
sayHi() { alert(this.name); }
|
||||
sayHi() { alert(this.name); }
|
||||
}
|
||||
|
||||
*!*
|
||||
// proof: User is the "constructor" function
|
||||
*/!*
|
||||
alert(User == User.prototype.constructor); // true
|
||||
alert(User === User.prototype.constructor); // true
|
||||
|
||||
*!*
|
||||
// proof: there are two methods in its "prototype"
|
||||
|
@ -129,7 +129,7 @@ class User {
|
|||
set name(value) {
|
||||
*/!*
|
||||
if (value.length < 4) {
|
||||
alert("Name too short.");
|
||||
alert("Name is too short.");
|
||||
return;
|
||||
}
|
||||
this._name = value;
|
||||
|
@ -146,7 +146,7 @@ user = new User(""); // Name too short.
|
|||
Internally, getters and setters are also created on the `User` prototype, like this:
|
||||
|
||||
```js
|
||||
Object.defineProperty(User.prototype, {
|
||||
Object.defineProperties(User.prototype, {
|
||||
name: {
|
||||
get() {
|
||||
return this._name
|
||||
|
@ -239,7 +239,7 @@ class User {
|
|||
*!*
|
||||
static staticMethod() {
|
||||
*/!*
|
||||
alert(this == User);
|
||||
alert(this === User);
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -252,7 +252,7 @@ That actually does the same as assigning it as a function property:
|
|||
function User() { }
|
||||
|
||||
User.staticMethod = function() {
|
||||
alert(this == User);
|
||||
alert(this === User);
|
||||
};
|
||||
```
|
||||
|
||||
|
@ -312,7 +312,7 @@ class Article {
|
|||
*!*
|
||||
static createTodays() {
|
||||
// remember, this = Article
|
||||
return new this("Todays digest", new Date());
|
||||
return new this("Today's digest", new Date());
|
||||
}
|
||||
*/!*
|
||||
}
|
||||
|
@ -322,7 +322,7 @@ let article = Article.createTodays();
|
|||
alert( article.title ); // Todays digest
|
||||
```
|
||||
|
||||
Now every time we need to create a todays digest, we can call `Article.createTodays()`. Once again, that's not a method of an article, but a method of the whole class.
|
||||
Now every time we need to create a today's digest, we can call `Article.createTodays()`. Once again, that's not a method of an article, but a method of the whole class.
|
||||
|
||||
Static methods are also used in database-related classes to search/save/remove entries from the database, like this:
|
||||
|
||||
|
|
Loading…
Add table
Add a link
Reference in a new issue