Last active
January 1, 2020 20:54
-
-
Save DmitriiNazimov/cf8eca8886879ae97817db3d31e97d2e to your computer and use it in GitHub Desktop.
[Синтаксис классов ES5 и ES6] #js #ООП
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ES 5 | |
function PersonType(name) { | |
this.name = name; | |
} | |
PersonType.prototype.sayName = function() { // Не пишем сразу в классе для экономии памяти, т.к. если прописать в классе, то метод создается у каждого экземпляра класса. Если прописать в прототипе (т.е. как тут на 5 строке), то получается один методов для всех экземпляров класса. | |
console.log(this.name); | |
} | |
var person = new PersonType("Nicholas"); | |
person.sayName(); | |
console.log(person instanceof PersonType); | |
console.log(person instanceof Object); | |
// выведет "Nicholas" | |
// true | |
// true | |
// ES 6 | |
class PersonClass { | |
// эквивалент конструктора PersonType | |
constructor(name) { | |
this.name = name; | |
} | |
// эквивалент метода PersonType.prototype.sayName | |
sayName() { | |
console.log(this.name); | |
} | |
} | |
let person = new PersonClass("Nicholas"); | |
person.sayName(); | |
console.log(person instanceof PersonClass); | |
console.log(person instanceof Object); | |
console.log(typeof PersonClass); | |
console.log(typeof PersonClass.prototype.sayName); | |
// выведет "Nicholas" | |
// true | |
// true | |
// "function" | |
// "function" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment