Home > Web Front-end > JS Tutorial > body text

JS中产生标识符方式的演变_javascript技巧

WBOY
Release: 2016-05-16 15:55:42
Original
1049 people have browsed it

一、ES5时代

var
function
我们知道 JS 不象其它语言 Java、Ruby等,它用来命名变量的只有关键字 var,不论何种类型数据都用 var 声明,当然弱类型并不代表该语言没有类型,它的类型在运行时(根据不同运算符)会隐式转换。而其它语言如Java,光声明数字的关键字就有 int、 float、double、long。

// JS
var num1 = 10;   // 整数
var num2 = 10.1;  // 浮点数
var str   = 'John'; // 字符串
var boo   = false; // 布尔
var obj   = {};  // 对象



Copy after login
// Java
int num1   = 10;
double num2  = 10.2;
String str   = "John";
Boolean boo = false;
 
Copy after login

JS 里标识符除了使用 var 产生,还有一个 function 关键字也可以产生标识符。function 类型声明的标识符的可能是函数、方法或构造器(类)。

// functions
function fetchData(url, param) {
  // ... 
}
 
// methods
var obj = {
  getUrl: function() {
  }
};
 
// class
function Person(name, age) {}
Person.prototype = {
}
 

Copy after login

二、ES6时代

var
function
let
const
class
可以看到,ES6 增加了3个可以产生标识符的关键字 let/const/class。let/const 用来声明变量,class 用来定义类。

// 定义普通变量
let name = 'John';
for (let i = 0; i < arr.length; i++) {
}
if (boo) {
  let obj = {};
  ...
}
 
// 定义常量
const PI = 3.1415926;
const $el = $('.nav');
 
// 定义类
class Point {
  constructor(x, y) {
    this.x = x;
    this.y = y;
  }
  toString() {
    return '('+this.x+', '+this.y+')';
  }
}
Copy after login

ES6时代,可以想象我们的代码风格里应该是 “少var多let”,let 和 const 都具有块级作用域,且不会发生变量提升。而声明类,也都会使用 class 了,class 关键字分担了 function 的部分任务。

以上所述就是本文的全部内容了,希望大家能够喜欢。

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!