holyya.com
2025-09-07 08:06:54 Sunday
登录
文章检索 我的文章 写文章
JavaScript中常见的声明方法及其应用
2023-06-17 00:00:24 深夜i     --     --
用于定义变量 作用域在函数内或全局作用域

在JavaScript中,我们可以使用几种不同的声明方法来定义变量、函数、对象以及类等。本文将讨论常见的JavaScript声明方法及其应用,并附上相应的代码案例。

1. var

代码案例:


function testVar() {

  var a = 10;

  if(true) {

    var a = 20;

    console.log(a);  // 输出20

  }

  console.log(a);    // 输出20

}

testVar();

2. let关键字:用于定义块级作用域的变量。

代码案例:


function testLet() {

  let a = 10;

  if(true) {

    let a = 20;

    console.log(a);  // 输出20

  }

  console.log(a);    // 输出10

}

testLet();

3. const关键字:用于定义常量,一旦声明则不能再次赋值。

代码案例:


function testConst() {

  const a = 10;

  // a = 20;  报错:Assignment to constant variable.

  console.log(a);  // 输出10

}

testConst();

4. function关键字:用于声明函数。

代码案例:


function add(x, y) {

  return x + y;

}

console.log(add(1, 2));   // 输出3

5. class关键字:用于声明类。

代码案例:


class Person {

  constructor(name, age)

    this.name = name;

    this.age = age;

  

  introduce() {

    console.log(`My name is ${this.name}, I'm ${this.age} years old.`);

  }

}

let p1 = new Person('Tom', 20);

p1.introduce();  // 输出:My name is Tom, I'm 20 years old.

关键词:JavaScript、声明方法、var、let、const、function、class

  
  

评论区

{{item['qq_nickname']}}
()
回复
回复
    相似文章