HTML(14-ECMA6(部分))

1. 什么是ecma6

  • ecmascript 6.0(简称 es6)

常用语法

let 关键字

用来声明变量。它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效

{
  let a = 100; // referenceerror: a is not defined.
  var b = 10; // 10
}

for循环的计数器,就很合适使用let命令

for (let i = 0; i < 100; i++) {}//referenceerror: i is not defined
console.log(i);

不允许重复声明

let a = 10;
let a = 20; //报错

let b = 10;
b = 20; //不报错

不存在变量提升

// var
console.log(foo); // undefined
var foo = 2;
 
// let
console.log(bar); // 报错
let bar = 2;

const 关键字

  • const声明一个只读的常量。一旦声明,常量的值就不能改变。
  • 也不存在变量提升
const p = 3
p // 3 
p = 4; //报错,不可更改

对象的简化写法

  • 属性的简化写法

var foo = 'n1';
var bar = 'n2';
 
var obj = {foo,bar};
//等同于
var obj = {foo:foo, bar:bar}
  • 方法的简化写法

{
    fn:function(){
    }
}
//可简化为
{
    fn(){
    }
}

class关键字

定义类

function point(x, y) {
  this.x = x;
  this.y = y;
}
 
point.prototype.tostring = function () {
  return '(' + this.x + ', ' + this.y + ')';
};
 
var p = new point(1, 2);
  • js传统方法中定义对象是通过构造函数,这种写法跟传统的面向对象语言(比如c++和java)差异很大,很容易让新学习这门语言的程序员感到困惑。

es6提供了更接近传统语言的写法,引入了class(类)这个概念。

class bar {
  dostuff() {
    console.log('stuff');
  }
}
 
var b = new bar();
b.dostuff() // "stuff"

constructor 构造方法

class bar{
    constructro() {
 
    }
}

类实例化的时, 构造函数会被自动调用

extends 继承

  • class之间可以通过extends关键字实现继承,这比es5的通过修改原型链实现继承,要清晰和方便很多。
class colorpoint extends point {}

上面代码定义了一个colorpoint类,该类通过extends关键字,继承了point类的所有属性和方法。

super

class colorpoint extends point {
  constructor(x, y, color) {
    super(x, y); // 调用父类的constructor(x, y)
    this.color = color;
  }
 
  tostring() {
    return this.color + ' ' + super.tostring(); // 调用父类的tostring()
  }
}

上面代码中,constructor方法和tostring方法之中,都出现了super关键字,它在这里表示父类的构造函数,用来新建父类的this对象。

子类必须在constructor方法中调用super方法,否则新建实例时会报错。这是因为子类没有自己的this对象,而是继承父类的this对象,然后对其进行加工。如果不调用super方法,子类就得不到this对象。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值