Skip to content

added more examples about static methods and properties #2982

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 33 additions & 0 deletions 1-js/09-classes/03-static-properties-methods/article.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,25 @@ alert( article.title ); // Today's digest

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.

Please note that when you create a method as a static method or assigning a method as a property, it wouldn't be available for objects!

```js run
class Article {
static alertName(name) { // create a static method
alert(`Hello ${name}`);
}
}

Article.alertAge = function(age) { // create a method as a property
alert(`Your age is ${age}`);
};

let article = new Article();

article.alertName("Fardin"); // Error! alertName is not defined!
article.alertAge(18); // Error! alertAge is not defined!
```

Static methods are also used in database-related classes to search/save/remove entries from the database, like this:

```js
Expand Down Expand Up @@ -128,6 +147,20 @@ That is the same as a direct assignment to `Article`:
```js
Article.publisher = "Ilya Kantor";
```
Also for static properties and direct assignmented properties, they are not available for created objects from class!

```js run
class Article {
static editor = "Fardin Ebrahimi";
}

Article.programmingLanguage = "JavaScript";

let article = new Article();

article.editor // Error! such property is not defined!
article.programmingLanguage //Error! such property is not defined!
```

## Inheritance of static properties and methods [#statics-and-inheritance]

Expand Down