Home > Web Front-end > Front-end Q&A > What are the 6 variable definition methods in es6

What are the 6 variable definition methods in es6

青灯夜游
Release: 2023-01-29 19:10:59
Original
2108 people have browsed it

6 ways to define variables in es6: 1. Use the keyword var to define the variable, the syntax is "var variable name = value;"; 2. Use the keyword function to define the variable; 3. Use the keyword const to define the variable , the syntax "const variable name = value;"; 4. Use the keyword let to define the variable, the syntax "let variable name = value;"; 5. Use the keyword import to define the variable; 6. Use the keyword class to define the variable.

What are the 6 variable definition methods in es6

The operating environment of this tutorial: Windows 7 system, ECMAScript version 6, Dell G3 computer.

es6 6 ways to declare variables


es5 only provides two ways to declare variables, namely var and function.

ES6 In addition to adding let and const commands, there are two ways to declare variables: import command and class command.

So, ES6 has a total of 6 ways to declare variables, namely var / function / let / const / import / class

(1) var command

var a ;  //undefined
var b = 1;
Copy after login
  • The variable scope declared by var is global or function level of.
  • Variables defined by var can be modified. If not initialized, undefined will be output and no error will be reported.
  • The variable declared by var is on the window. Use let or const to declare the variable. This variable will not be placed on the window.
  • Many languages ​​​​have block-level scopes, but JS does not. It uses var to declare variables and use function (it can also be said to use curly brackets '{ }') to divide the scope, but the curly brackets "{ }" cannot limit the scope of var, so variables declared with var have the effect of variable promotion.

(2)function command

function add(a) {
  var sum = a + 1;
  return sum;
}
Copy after login
  • declares a new variable named add and assigns it A function definition. The content between
  • { } is assigned to add.
  • The code inside the function will not be executed immediately when declared, but is simply stored in variables for future use.

(3) cosnt command

const a;     //报错,必须初始化
const b = 1; 
b = 2;      //报错,TypeError: Assignment to constant variable.
Copy after login
  • const defines a constant and must be initialized.
  • The pointer of a constant declared with the const keyword cannot be changed. What is said here is that the constant pointer cannot change, but the value of the memory space pointed by the pointer can change.
    For example:
const obj = {};
obj.n = 123;
obj; // { n: 123 }
obj = { x: 1 }; // TypeError: Assignment to constant variable.
Copy after login

const declares an object named obj. The obj pointer points to an object. Adding attributes to the object means adding data to the data of the object. The address pointing to the object stored in obj has not been changed, so it can be executed successfully. However, the operation of reassigning obj changes the pointer pointing to obj, so the operation fails and an error is thrown.
The same is true for basic types, because the data of basic types is stored directly on the stack, and the constant name directly points to the data at this address. Once the value is changed, the pointer address will change, so the value cannot be changed. Illusion.

  • This variable is a global variable, or a global variable within the module, with block-level scope.

  • If a variable is assigned only once when it is declared and will never be reassigned in other lines of code, then const should be used, but the initial value of the variable may Will be adjusted in the future (constant variable).

  • Const-defined variables are generally used when requiring a module or define some global constants.

  • A constant cannot have the same name as other variables or functions in its scope.

(4) let command

Requires "javascript strict mode": 'use strict';

----There is no variable promotion

console.log(a);  //ReferenceError: a is not defined
let a = "apple";
 
console.log(b);  //undefined
var b = "banana";
Copy after login

The variable b is declared with var and there is variable promotion, so when the script starts running, b already exists, but has not been assigned a value, so it will Output is undefined.
There is no variable promotion when variable a is declared with let. Before declaring variable a, a does not exist, so an error will be reported.

Duplicate declarations are not allowed

let a = 1;
let a = 2;
var b = 3;
var b = 4;
a  // Identifier 'a' has already been declared
b  // 4
Copy after login

let can only be declared once, var can be declared multiple times

Block-level scope (that is, only Valid in a { ​​})

{
  let a = 0;
  a   // 0
}
a   // 报错 ReferenceError: a is not defined
Copy after login

After the let definition is used inside the function, it has no impact on the outside of the function

You can assign a value to the variable when declaring it, and the default value is undefined, you can also assign a value to the variable later in the script. It cannot be used before declaration (temporary dead zone)

let a;
console.log(a);    //  undefined
console.log(b);   // ReferenceError: b is not defined
let b = 1;
a = 2;
console.log(a);     // 2
Copy after login

Note: ES6 clearly stipulates that if there is let or const in the code block , the code block will form a closed scope from the beginning of the block to the variables declared by these commands. Within a code block, using the variable PI before declaring it will result in an error.

var PI = "a";
if(true){
  console.log(PI);  // ReferenceError: PI is not defined
  const PI = "3.1415926";
}
Copy after login

(5) import command

import is used to load files. What is received in the curly brackets is an or Multiple variable names, these variable names need to be the same as the variable names you want to import.

举个栗子:你想要导入action.js文件中的某一个变量,这个变量里保存了一段代码块,所以你要写成:import { Button } from 'action',这个时候,你就从action.js中获取到了一个叫 Button 的变量,既然获取到了,你就可以对Button里的代码猥琐欲为了

如果想为输入的变量重新取一个名字,import命令要使用as关键字,将输入的变量重命名,比如:

import { NewButton as Button } from 'action.js';
Copy after login

上面的代码表示从action.js文件中,获取一个变量名称叫做Button的代码段,然后你又声明了一个变量 NewButton ,将 Button 保存在 NewButton

(6) class命令

在es5中我们是使用构造函数实例化出来一个对象,那么构造函数与普通的函数有什么区别呢?其实没有区别,无非就是函数名称用首字母大写来加以区分,这个不用对说对es5有了解的朋友都应该知道。
但是es5的这种方式给人的感觉还是不够严谨,于是在es6中就换成了class,就是把es5中的function换成了class,有这个单词就代表是个构造函数,然后呢对象还是new出来的,这一点并没有变化。

类的使用

从里面的代码我们可以看到除了function变成了class以外,其它的跟es5一样

class Coder{
    name(val){
        console.log(val);
    }}
 let shuang= new Coder;shuang.name('shuang');
Copy after login

类的传参

在es6中的对象的属性都是写在constructor里面,方法都是在原型身上。在这里面的代码用constructor约定了两个参数,然后用add()方法把参数相加,这个地方跟以前不太一样,所以需要多注意一下。

class Coder{
    name(val){
        console.log(val);
        return val;
    }

    constructor(a,b){
        this.a=a;
        this.b=b;
    }
 
    add(){
        return this.a+this.b;
    }}
 let shuang=new Coder(1,2);console.log(shuang.add());
Copy after login

class的继承

class的继承就是用extends

class shuang extends Coder{
 }
 let shuang=new shuang;shuang.name('Angel爽');
Copy after login

声明一个shuang的新类,用extends继承了Coder,调用里面的name方法,发现也是可以输出的。

学习总结:


一、用关键字var声明变量

1、var声明的全局对象是顶级对象(window)的属性;

2、用var在函数外声明的对象为全局变量,在函数内声明的对象为局部变量;

3、用var可以对同一对象重复声明和赋值;

4、用var声明的对象具有变量提升的作用(声明提前,赋值不提前);

二、用关键字function声明变量

1、用function声明的函数对象具有变量提升的作用(声明提前,赋值不提前);

2、function声明的函数对象是顶级对象(window)的属性;

三、用关键字let声明变量

1、用let声明的变量在块级作用域内有效;

2、let声明的变量不存在变量提升

3、let声明的变量存在暂时性死区(即同一个块级作用域中,在let声明该变量的语句之前,该变量已经存在,但是不能使用);

4、在同一个作用域内,对于let声明的变量不能重复声明。

四、用关键字const声明变量

1、const命令声明的值一旦声明,就不能再次改变;

2、const声明变量时,必须立即初始化,否则会报错(因为值一旦声明不可改变);

3、const声明的变量不存在变量提升

4、const声明的变量存在暂时性死区;

5、const声明的变量只在块级作用域内有效;

6、const变量在同一个作用域内不能重复声明。

五、关于变量提升

1、只有声明本身会被提升,而赋值操作不会被提升。

2、变量会提升到其所在函数的最上面,而不是整个程序的最上面。

3、函数声明会被提升,但函数表达式不会被提升。

4、函数声明的优先级高于普通变量申明的优先级,并且函数声明和函数定义的部分一起被提升。

5、同一个变量只会声明一次,其他的会被忽略掉。

【相关推荐:javascript视频教程web前端

The above is the detailed content of What are the 6 variable definition methods in es6. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template