ES6系列学习(6)模块、Babel、Polyfill、ES6继承

1.ES6模块

//config.js
export const apiKey = 'abc123';
export const age = 12;

export function greet(name){

};

//
import { apiKey ,age , greet} from './config'

slug:可以将各种各样的用户名转换成-连接的用户名,地址:https://www.npmjs.com/package/slug

2.使用SystemJS打包ES模块

和Webpack一样是打包工具,但是不用复杂配置。

https://www.npmjs.com/package/systemjs

3.Babel

babel中文网:https://www.babeljs.cn/

4.Polyfill

babel只能转换语法而不是去增加或修改原有ES6新的属性和方法。polyfill就是为了解决这种情况,也能抚平不同浏览器之间对js实现的差异。

babel/polyfill使用:https://www.babeljs.cn/docs/babel-polyfill

5.原型继承

//ES5的原型继承
function User(name,email){
	this.name = name;
	this.email = email;
}

User.prototype.info = function(){
	console.log('Hi I am ...');
}

const codecasts = new User('','');
codecasts.info()

//ES6的class继承
class User{
	//类中构造函数
	constructor(name,email){
		this.name = name;
		this.email = email;
	}
	//类中方法
	info(){

	}
	//静态方法(只能在原型对象上调用,不能在实例上调用,例如Array.from())
	static description(){

	}
	
	//get/set设置和获取属性
	set github(value){
		this.girhubName = value;
	}
	get github(){
		return `https://github.com/${this.githubName}`
	}

}

const codecasts = new User('','');
codecasts.github = 'laravist';
codecasts.github

ES5和ES6的继承:

专门写一篇介绍

6.类的扩展

继承一个类:

class Aimal{
	constructor(name){
		this.name;
		this.belly = [];
	}
	
	eat(food){
		this.belly.push(food);
	}

}

class Dog extends Animal{
	constructor(name,age){
		super(name);   //类似于es5的Animal.call(this,name,age);
		this.age = age;
	}
	bark(){
		console.log('');
	}
}

const lucky = new Dog('lucky',2);
lucky

子类必须在constructor方法里调用super方法,否则不能新建实例。这是因为子类没有属于自己的this对象,而是继承了父类的this对象而对其进行加工。显然,只有调用了super方法之后,才可以使用this。

7.ES6的class扩展内建对象数组

下面两种继承方式输出结果不一样

//1 super()创建this值指向基类Array,MyArray这个子类在这个基类this上修改,所以this的值可以访问基类上的功能的
class MyArray extends Array{
	constructor(){
		super();
	}
}

//2 子类MyArray创建this的值,this的值指向MyArray的实例,然后调用基类构造函数,Array的其他属性会修饰这个this
function MyArray(){
	Array.apply(this,arguments);
}

const colors = new MyArray();
colors[0] = 'red';
console.log(colors.length);   //undefined

colors.length = 0;
console.log(colors[0])   //red
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值