JavaScript中产生标识符方式的演变

本文记录下JS中产生标示符方式的演变,从ES5到ES6,ES5及其之前是一种方式,只包含两种声明(var/function),ES6则增加了一些产生标识符的关键字,如 let、const、class。

 

一、ES5时代

  1. var
  2. 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      = {};    // 对象

 

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

 

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

// functions
function fetchData(url, param) {
    // ...  
}

// methods
var obj = {
    getUrl: function() {
    }
};

// class
function Person(name, age) {}
Person.prototype = {
}

 

二、ES6时代

  1. var
  2. function
  3. let
  4. const
  5. 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+')';
  	}
}

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

 

三、ES7时代

...

 

 

相关:

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/let

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/const

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Statements/class

posted on 2015-06-12 07:13  snandy  阅读(2085)  评论(1编辑  收藏  举报