What is a class in js
Editor to share with you what is a class in js, I believe that most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's go to understand it!
What is a class?
Class (class) is a new way to write constructors in JS. It is the syntax sugar that uses the constructor, which is still prototype and prototype-based inheritance at the bottom.
/ ES5 Version function Person (firstName, lastName, age, address) {this.firstName = firstName; this.lastName = lastName; this.age = age; this.address = address;} Person.self = function () {return this;} Person.prototype.toString = function () {return "[object Person]";} Person.prototype.getFullName = function () {return this.firstName + "+ this.lastName } / / ES6 Version class Person {constructor (firstName, lastName, age, address) {this.lastName = lastName; this.firstName = firstName; this.age = age; this.address = address;} static self () {return this;} toString () {return "[object Person]" } getFullName () {return `${this.firstName} ${this.lastName}`;}}
Override the method and inherit from another class.
/ ES5 VersionEmployee.prototype = Object.create (Person.prototype); function Employee (firstName, lastName, age, address, jobTitle, yearStarted) {Person.call (this, firstName, lastName, age, address); this.jobTitle = jobTitle; this.yearStarted = yearStarted;} Employee.prototype.describe = function () {return `I am ${this.getFullName ()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted} `;} Employee.prototype.toString = function {return "[object Employee]" } / / ES6 Versionclass Employee extends Person {/ / Inherits from "Person" class constructor (firstName, lastName, age, address, jobTitle, yearStarted) {super (firstName, lastName, age, address); this.jobTitle = jobTitle; this.yearStarted = yearStarted;} describe () {return `I am ${this.getFullName ()} and I have a position of ${this.jobTitle} and I started at ${this.yearStarted} ` } toString () {/ / Overriding the "toString" method of "Person" return "[object Employee]";}}
So how do we know it uses prototypes internally?
Class Something {} function AnotherSomething () {} const as = new AnotherSomething (); const s = new Something (); console.log (typeof Something); / / "function" console.log (typeof AnotherSomething); / / "function" console.log (as.toString ()); / / "[object Object]" console.log (as.toString ()); / / "[object Object]" console.log (as.toString = = Object.prototype.toString); / / trueconsole.log (s.toString = Object.prototype.toString) / / true above is all the content of this article "what is a Class in js". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!