let,const 用途和var类似
var name="zac";
while(true){
var name="nic";
console.log(name);
break;
}
console.log(name);
// nic
// nic
两次输出都是nic 因为es5 只有全局作用域和函数作用域,没有块级作用域
let 为javascript新增了块级作用域 let 只在所在的代码块内有效
let name="nic";
while(true){
let name="zz";
console.log(name);//zz
break;
}
console.log(name);//nic
var带来的不合理场景 计数的循环变量泄露为全局变量
var a=[];
for(var i=0;i<10;i++){
a[i]=function(){ console.log(i);}
}
a[6]();
var a=[];
for(let i=0;i<10;i++){
a[i]=function(){ console.log(i);}
}
a[6]();//6
const 也用来声明变量,但是声明的是常量,一旦声明,常量的值就不能改变
原型 ,构造函数 继承
SE6引入了class(类)这个概念,新的class写法让对象原型的写法更加清晰,更像面向对象编程的语法。
class Animal{
constructor(){ this.type="animal";}
says(say){console.log(this.type+"says"+say);}
}
let animal=new Animal();
animal.says("hello");// animal says hello
//上面代码首先用class定义了一个类,可以看到里面有一个constructor方法,这就是构造函数
// this关键字代表实例对象,consructor内定义的方法和属性是实例对象自己的,而constrcutor外定义的方法和属性则是所有实例对象可以共享的
function Point(x,y){
this.x=x;
this.y=y;
}
Point.prototype.toString=function(){
console.log("x"+this.x+" y "+this.y);
}
class Point{
constructor(x,y){
this.x=x;
this.y=y;
}
toString(){
console.log("x"+this.x+" y "+this.y);
}
}
上面两个函数相同
extends super()
Class Cat extends Animal{
constructor(){
super();
this. type="cat";
}
}
let cat=new Cat()
cat.says("hello");// cat says hello
Class之间可以通过extends 关键字实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便的多。 上面定义了一个Cat类,通过extends 继承了Animal类的所有属性和方法
ES6的继承机制:实质是先创造父类的实例对象this(所以必须调用super方法)在用子类的构造函数修改this