当前位置:网站首页>Es6--- > arrow function, class, modularization
Es6--- > arrow function, class, modularization
2022-07-28 07:02:00 【Hahaha~】
Arrow function :
One 、 Definition
- Only definable For resolution this The problem of Cannot be used to create objects
let fn = (n1, n2) => {
return n1 + n2
}
var re = fn(1, 2)
console.log(re) // 3
- When there is only one formal parameter of the arrow function You can omit the whole parameter parentheses
var fn = a => a
fn(10); //10- When an arrow function has no or multiple arguments Use () Cover up
var fn = (a,b) => a+b;
fn(1,2); //3- When the arrow function body has only one line of statements and needs to return results It can be omitted {} and return The results will return automatically
var fn = (a, b) => a * b
var re = fn(10, 20)
console.log(re) //200- When an arrow function body has multiple lines use {} Wrap it up Represents a code block
var fn = (a,b) => {
let result = a+b;
return result;
}
fn(1,2); // 3- When the arrow function returns an object , To distinguish between code blocks , Use () Wrap objects
var fn = (id,name) => ({id: id, name: name});
f(41,559); // {id: 41, name: 559}- When the number of shape arguments is different ... The remaining parameter must be the last parameter
var fn = (a, ...b) => {
console.log(b) //[20, 30]
}
fn(10, 20, 30)
//a=10Two 、 effect
- There's nothing in the arrow function this object , Solve the problem inside the function this Direction problem of
In the arrow function this Is the closest nesting level to it function/ Method the caller of this function No is window
Example :
var obj = {
say: function () {
var obj2 = {
say: () => {
console.log(this) //{say: ƒ}
}
}
obj2.say()
}
}
obj.say()
/* analysis :
this On the upper floor function Is written in the book say In the method
The caller calling this method is obj object
therefore this representative obj object
*/Example :
var obj = {
say: () => {
console.log(this)
}
}
obj.say()
/* analysis :
this The upper scope of the arrow function is the global scope No, function And methods
therefore this representative window
*/3、 ... and 、 summary
- Have an arrow
- The arrow is preceded by parentheses , Put formal parameters , Parentheses can be omitted when there is only one formal parameter ;
- After the arrow is the function body ;
- If the function body has only one statement , No, {}, The return value at this time does not need return;
- Inside the arrow function this Always point to the nearest function Inside this;
- Methods in objects , Try not to use arrow functions ;
- There is no... In the arrow function arguments You can use …reset, All arguments except formal parameters are received It's an array type
class
One 、 Concept
Preface :
js It's a be based on Object oriented design Single thread Of static state Scripting language
js Not an object-oriented language Based on The underlying mechanism is still the idea of prototype
Classes are introduced to better handle js Grammatical features of a language designed to be object-oriented
stay ES6 in ,class ( class ) Templates are introduced as objects , Sure adopt class Keyword definition class
class The essence is function
It can be seen as a grammatical sugar , Make the writing of object prototypes clearer 、 It's more like the syntax of object-oriented programming
Class cannot be declared repeatedly
Class definitions are not promoted , This means that the class must be defined before access , Otherwise you will report an error
Two 、 Definition
Name the class :
class Person{}
var p1=new Person()An anonymous class :
var fn=class{}
var f1=new fn()notes : In strict mode, the first letter of the class name must be capitalized
3、 ... and 、 Class
attribute :ES6 Variables cannot be defined directly in the class of , Variables are defined in constructor in
class Person {
constructor() {
this.name = "hahah"; // Defining variables
}
}
let p = new Person();
console.log(p.name);Method
constructor Method Is the default method of the class , Called when creating an object of a class , Also known as class constructor
In a class There is and only one Construction method If don't write constructor An empty constructor is built in by default
class Person{ constructor(){ console.log("haha") } } var p = new Person() // Will perform constructor MethodPrototype method : No need to use function keyword , adopt “ object . Prototype method ” call .
class Person { say() { console.log("haha"); } add(a, b) { console.log(a + b); } } let p = new Person(); p.say(); //haha p.add(1, 2); //3Static methods : Use static modification , There is no need to create an object when calling , Directly through “ Class name . Static methods ” call
class Person { static sum(a, b) { console.log(a + b); } } Person.sum(1, 2);
Example :
class Teacher {
constructor(name) {
this.name = name
}
b = 100 // Object properties Don't change the overall situation
say() { // How to prototype objects
console.log(this.name) //lili
}
static say3() {} // Static methods Use the class name to access
static a = 20 // Static attribute Use the class name to access
}
var t1 = new Teacher("lili")
console.log(t1) //b: 100 name: "lili"
t1.say()
console.log(Teacher.say3) //ƒ say3() {}Four 、 Inherit
Solve code reuse
Use extends Keyword implementation inheritance
Subclasses can inherit all methods and properties in the parent class
A child class can only inherit one parent class ( Single inheritance ), A parent class can have more than one subclass
There must be super() To specify the constructor of the calling parent class , And in the subclass construction method first line
If the subclass has the same methods and properties as the parent class , Subclasses will be preferred ( Cover )
- super() Call the parent constructor , There must be , And in the first line of the subclass constructor
class Person {
constructor(arg) {
this.life = 1
}
}
class Student extends Person {
constructor(arg) {
super() // Give Way Student The objects created by class are Person Class Write in the first row
this.name = arg
}
}
var s1 = new Student("lili")
console.log(s1) //Student {life: 1, name: 'lili'} Having a parent life attribute Example :
class People {
// Parent class constructor
constructor() {
this.a = 100; // Variables defined in the parent class
console.log("People constructor");
}
// Prototype method
eat() {
console.log("eat...")
}
// Static methods
static play() {
console.log("play...")
}
}
class Student extends People {
// Subclass construction method
constructor() {
super(); // Call the parent constructor , There must be , And in the first line of the subclass constructor
this.b = 200; // Variables defined by subclasses
console.log("Student constructor");
}
study() {
console.log("study...");
}
}
let s = new Student();
console.log(s.a,s.b); //100,200
s.eat();
s.study();
Student.play();modularization
One 、 Concept
The modular design idea is : At compile time, you can determine the dependencies of the module and the input and output variables
Modularity is divided into export (export) And Import (import) Two modules
js The code is written to the page 3 Ways of planting :
1. Inline :js The engine is going to execute some of the tags ( event ) Properties of the
2. The embedded
3. Import src My address is a js The path of Will load js code (jsonp)
Two 、 Modular features
ES6 The module automatically turns on strict mode , Whether or not you add use strict;
Various types of variables can be imported and exported in the module , Such as function , object , character string , Numbers , Boolean value , Class etc.
Each module has its own context ( Scope ), Variables declared in each module are local variables , Does not contaminate the global scope
Each module is loaded only once ( Is a singleton ), If you load the same file in the same directory , Read directly from memory
3、 ... and 、 Module import and export
export export :
And default Associated use And one js Module There can only be one export default sentence
var a=20; export default a; // Export a variable export var fn=function(){}; // Export a function- A separate ( On demand ) export The exported identifier must be used to import on demand , There can be multiple separate exports
model.js in :
export var num=100 // You can write many times
export function tool () {return obj}
export default {a:1,b:2} // Write only once
html In file :
import {num,tool} from "model.js" // Import on demand
import {a} from "model.js" // Import on demand
import all from "model.js" // Import all import Import :
And from Associated use , here script Labeled type Must be set to module
The singleton pattern : Repeat the same sentence several times import sentence , that It's only going to be executed once , It's not executed many times .
import The same module , Declare different interface references , Will declare the corresponding variable , But only once import
<script type="module">
//type="module" module: es6 Interpreter babel It is the built-in software of browser
// because js Read the external file and encode need babel Software to decode
import a from 'js File path '
</script>边栏推荐
- MOOC翁恺C语言 第六周:数组与函数:1.数组2.函数的定义与使用3.函数的参数和变量4.二维数组
- Applets: lifecycle
- 防火墙——iptables防火墙(四表五链、防火墙配置方法、匹配规则详解)
- Custom component -- pure data field & component life cycle
- Applet creation component
- MOOC翁恺C语言 第四周:进一步的判断与循环:1.逻辑类型与运算2.级联和嵌套的判断
- LNMP搭建过程详解
- MOOC翁恺C语言 第四周:进一步的判断与循环:3.多路分支4.循环的例子5.判断和循环常见的错误
- 单元测试框架Jest搭配TypeScript的安装与配置
- Custom components -- styles
猜你喜欢
随机推荐
Iptables firewall
Software testing (concept)
Hdu-5783 divide the sequence (greedy water question)
Tcp/ip five layer model
Ten thousand words summarize and realize the commonly used sorting and performance comparison
Use powercli to create a custom esxi ISO image
MOOC翁恺 C语言 第三周:判断与循环:2.循环
Understanding of C language EOF
Method of designing test cases
KVM hot migration
Centos7 deploy MySQL database server
Wechat applet custom compilation mode
Custom components -- slots
Applets: WSX scripts
Hdu-5806-nanoapelovesequence Ⅱ (ruler method)
What's a good gift for Tanabata? Niche and advanced product gift recommendation
On cookies and session
Esxi community network card driver updated again
Test life | second tier cities with an annual salary of more than 40W? How did you achieve 100% salary increase under the epidemic?
QT uses MSVC compiler to output Chinese garbled code









