The class keyword of es6 is used to quickly define a "class"; the essence of class is function, which can be regarded as a syntactic sugar, making the writing of object prototypes clearer and more like the syntax of object-oriented programming. There is no variable promotion when promoting a class. All methods of a class are defined on the prototype attribute of the class. Calling a method on an instance of a class is actually calling a method on the prototype.
The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.
Basics
es6 introduces the concept of Class. The class keyword is used to quickly define a "class". The new class writing method makes the writing of object prototypes clearer, more like the syntax of object-oriented programming, and easier to understand.
In fact, the concepts of prototype and constructor are still used behind it.
Strict mode There is no need to use use strict because as long as the code is written within classes and modules, strict mode can only be used.
There is no variable promotion when improving class (due to inheritance, you must ensure that the subclass is defined after the parent class).
All methods of a class are defined on the prototype attribute of the class. Calling methods on instances of the class is actually calling methods on the prototype. Prototype methods can be called through instance objects, but not When calling through the class name, an error will be reported
class is used to define a class for es6
In fact, class is just a Syntax sugar is another way of writing constructor
(Syntax sugar is an elegant solution at the syntax level to avoid coding errors and improve coding efficiency. Simply put, it is portable. Just writing method)
Look at the code
class Person{ } console.log(typeof Person) //funciton console.log(Person.prototype.constructor === Person) //true
Use and look at the code
The usage is the same as using the constructor. Use new to generate object instances
class person2 { } let json = new person2;
Properties and methods
The properties and methods defined in the constructor are instance properties and methods that are called on this, otherwise they are prototype properties and methods
class Person { constructor (name) { this.name = name //constructor内定义的方法和属性是实例对象自己的, } say () { //而constructor外定义的方法和属性则是所有实例对象可以共享的 注意! console.log('hello') } } let jon = new Person() jon.hasOwnPrototype('name') //true jon.hasOwnPrototype('say') //false
Static methods
Methods that can be called directly through the class without passing the instance object, where this points to the class itself
class Person { static doSay () { this.say() } static say () { console.log('hello') } } Person.doSay() //hello *********************************************************************************************** //静态方法可以被子类继承 class Sub extends Person { } Sub.doSay() // hello //静态方法可以通过类名调用,不能通过实例对象调用,否则会报错 class Person { static sum(a, b) { console.log(a + b) } } var p = new Person() Person.sum(1, 2) // 3 p.sum(1,2) // TypeError p.sum is not a function
name attribute
## The #name attribute returns the name of the class, which is the name immediately following class.class Person { } Person.name // Person
this defaults to an instance of the class.
If there is this inside a class method, an error is likely to be reported if this method is used aloneIf this points to the wrong direction 1. Use the arrow function 2. Bind it in the constructor this
Value function (getter) and storage function (setter)class Person {
get name () {
return 'getter'
}
set name(val) {
console.log('setter' + val)
}
}
let jon = new Person()
jon.name = 'jon' // setter jon
jon.name // getter
//Class declaration cannot be repeated
class Person {}class Person {}
// TypeError Identifier 'Person' has already been declared
constructor keyword
- Constructor method
- The constructor method is the default method of the class. When an object instance is generated through the new command, this method is automatically called (the instance object this is returned by default).
- A class must have a constructor method. If it is not explicitly defined, an empty constructor method will be added by default.
- A class can only have one special method named "constructor". If the class contains multiple constructor methods, a SyntaxError will be thrown.
class Person { constructor(x, y) { this.x = x //默认返回实例对象 this this.y = y } toString() { console.log(this.x + ', ' + this.y) } }
What is constructor?
Each class must have a constructor. If there is no explicit declaration, the js engine will automatically add an empty constructor
class person3 { } //等于 class person3 { constructor(){} }
Attention When declaring a method in a class, do not add the function keyword before the method Do not separate methods with commas, otherwise an error will be reported All methods defined inside the class are non-enumerableNote that the attributes of the instance are the same as es5 unless they are explicitly defined on itself (i.e. this object). Defined on the prototype
class Point { constructor(x,y){ this.x = x; this.y = y; } toString(){ return `this.x + this.y`; } } var point = new Point(); point.toString() //(2,3) point.hasOwnProperty("x") //true point.hasOwnProperty("y") //true 在这x&&y都是实例对象point自身的属性(因为定义在this变量上) // 所以返回true point.hasOwnProperty("toString") //false toString是原型对象的属性 (因为定义在Point类上) //所以返回false point._proto_.hasOwnProperty("toString") //true //加两个实例 var p1 = new Point(); var p2 = new Point(); p1._proto_ === p2._proto_ //true 这个不建议使用 //上面代码中 p1和p2 都是point的实例 他们的原型都是Point.prototype 所以 _proto_属性是相等的 //即是说 可以通过实例的_proto_ 属性为 "类" 添加方法
super keyword
The super keyword is used to access and call functions on the parent class. You can also call the constructor of the parent class. Ordinary functions of the parent classclass Father { constructor (surname){ this.surname = surname } say(){ console.log("你的名字" + this.surname) //你的名字锤子 } } //在这里 子继承父类 class Son extends Father { constructor(surname,name){ super(surname) this.name = name } say(){ super.say() console.log('调用普通' + this.name) //调用普通铁的 } } var son = new Son('锤子',"铁的") son.say() console.log(son) //打印 {surname: "锤子", name: "铁的" //在子类的构造函数如果使用 super 调用父类的构造函数 必须写在 this之前 //还可以 调用父类的普通方法 //在es6中 类没变量提升 必须先定义 才能通过实例化对象类里面的 共有属性 和方法 通过this 调用 //类 里面的this 代表什么 //constructor 里面this指向实例对象 // 方法里面this 代表 方法的 调用者
extends inheritance
Inheritance means that the son inherits the father's business. In reality, the subclass in the program can inherit some methods and attributes from the parent classA major feature of object-oriented inheritance can reduce the writing of code and facilitate the extraction of public content keywords extends
class Father { constructor (surname){ this.surname = surname } say(){ //父级Father里面有一个方法 say() console.log("你的名字" + this.surname) } } class Son extends Father { //在这里Son 继承了 Father父级里面的方法 关键字extends } var son = new Son('锤子') //new 出来实例 son.say() //打印 你的名字锤子
类的方法
class Person { constructor(name, age) { // 构造函数,接收一个name和age this.name = name this.age = age } say(){ // 一个方法 //注意类里面的方法不加function关键字 方法与方法之间不用,号隔开 console.log("你好",this.name) } // ....sayWhat(){} saySome(){} } var person = new Person('老王',44) //调用方法 person.say() //老王 //在类的实例上调用方法 其实就是调用 原型上的方法
类的表达式
与函数一样 calss 也可以使用表达式的形式定义 采用class表达式 可以写出立即执行的Class!!
注意与函数表达式类似 类表达式在他们被求值前也不能使用(即赋值变量 之前调用) 但 与函数定义不同 虽然函数声明可以提升 但类不能
类表达式(类定义)
类表达式可以是被命名的或匿名的
匿名类
let Person = class { constructor(x, y) { this.x = x this.y = y } }
命名的类
let Person = class Person { constructor(x, y) { this.x = x this.y = y } } const Mycalss = class Me { getClassName(){ return Me.name; } }; //这里用 表达式(即赋值变量一个) //注意! 这个类的名字是Mycalss而不是 Me Me只在Class的内部代码可用 指代当前类 let inst = new Mycalss(); inst.getClassName() //Me Me.name //报错 Me只在Class内部有定义
采用class表达式 可以写出立即执行的Class!!
let person = new class { constructor(name) { this.name = this.name; } sayname(){ console.log(this.name); } }("常东东") //这段代码中class是立即执行的实例
补充案例
class Animal { //class定义了一个“类” constructor(){ this.type = 'animal' //有一个constructor方法,这就是构造方法 //this关键字则代表实例对象 } //constructor内定义的方法和属性是实例对象自己的,而constructor外定义的方法和属性则是所有实例对象可以共享的 注意! says(say){ console.log(this.type + ' says ' + say) } } let animal = new Animal() animal.says('hello') //animal says hello class Cat extends Animal { //通过extends关键字实现继承 //定义了一个Cat类,该类通过extends关键字,继承了Animal类的所有属性和方法。 constructor(){ super() //super关键字 它指代父类的实例(即父类的this对象)子类必须在constructor方法中调用super方法,否则新建实例时会报错。 this.type = 'cat' //这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。 } } let cat = new Cat() cat.says('hello') //cat says hello
【相关推荐:javascript视频教程、编程视频】
The above is the detailed content of What does es6 class do?. For more information, please follow other related articles on the PHP Chinese website!

HTML and React can be seamlessly integrated through JSX to build an efficient user interface. 1) Embed HTML elements using JSX, 2) Optimize rendering performance using virtual DOM, 3) Manage and render HTML structures through componentization. This integration method is not only intuitive, but also improves application performance.

React efficiently renders data through state and props, and handles user events through the synthesis event system. 1) Use useState to manage state, such as the counter example. 2) Event processing is implemented by adding functions in JSX, such as button clicks. 3) The key attribute is required to render the list, such as the TodoList component. 4) For form processing, useState and e.preventDefault(), such as Form components.

React interacts with the server through HTTP requests to obtain, send, update and delete data. 1) User operation triggers events, 2) Initiate HTTP requests, 3) Process server responses, 4) Update component status and re-render.

React is a JavaScript library for building user interfaces that improves efficiency through component development and virtual DOM. 1. Components and JSX: Use JSX syntax to define components to enhance code intuitiveness and quality. 2. Virtual DOM and Rendering: Optimize rendering performance through virtual DOM and diff algorithms. 3. State management and Hooks: Hooks such as useState and useEffect simplify state management and side effects handling. 4. Example of usage: From basic forms to advanced global state management, use the ContextAPI. 5. Common errors and debugging: Avoid improper state management and component update problems, and use ReactDevTools to debug. 6. Performance optimization and optimality

Reactisafrontendlibrary,focusedonbuildinguserinterfaces.ItmanagesUIstateandupdatesefficientlyusingavirtualDOM,andinteractswithbackendservicesviaAPIsfordatahandling,butdoesnotprocessorstoredataitself.

React can be embedded in HTML to enhance or completely rewrite traditional HTML pages. 1) The basic steps to using React include adding a root div in HTML and rendering the React component via ReactDOM.render(). 2) More advanced applications include using useState to manage state and implement complex UI interactions such as counters and to-do lists. 3) Optimization and best practices include code segmentation, lazy loading and using React.memo and useMemo to improve performance. Through these methods, developers can leverage the power of React to build dynamic and responsive user interfaces.

React is a JavaScript library for building modern front-end applications. 1. It uses componentized and virtual DOM to optimize performance. 2. Components use JSX to define, state and attributes to manage data. 3. Hooks simplify life cycle management. 4. Use ContextAPI to manage global status. 5. Common errors require debugging status updates and life cycles. 6. Optimization techniques include Memoization, code splitting and virtual scrolling.

React's future will focus on the ultimate in component development, performance optimization and deep integration with other technology stacks. 1) React will further simplify the creation and management of components and promote the ultimate in component development. 2) Performance optimization will become the focus, especially in large applications. 3) React will be deeply integrated with technologies such as GraphQL and TypeScript to improve the development experience.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Zend Studio 13.0.1
Powerful PHP integrated development environment

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.