es6中的类及es5类的实现

类的特点

1.类只能通过new得到

在es6中类的使用只能是通过new,如果你将它作为一个函数执行,将会报错。

//es6的写法
class  Child {
	constructor() {
		this.name  =  1;
	}
}
let  child  =  new  Child();
console.log(child.name)//1
//如果直接方法调用的形式,会报错
let  child  =  Child();//Class constructor Child cannot be invoked without 'new'

es5中的class其实就是一个方法,没有关键字class

//es5中类的写法,但是这样直接用方法名调用并不会报错
var  Person  = (function () {
	function  Person(name) {
		this.name  =  name;
	}
	Person.prototype.SayHello  =  function () {
		window.alert("My name is "  +  this.name  +  ".");
	};
	return  Person;
})();
var  p  =  Person()//不报错

为了实现类似于es6中的调用检查,我们需要自己手写一个调用检查的函数。这个函数的原理就是用当前的this和构造函数进行比较,如果这个this指向的window,那么可以看出是用通过方法名直接调用的,如果this是构造函数那么就是通过new得到的

var  Person  = (function () {
//类的调用检测
	function  _classCheck(instance, constructor) {
		if (!(instance  instanceof  constructor)) {
			throw  new  Error('Class constructor Child cannot be invoked without new')
		}
	}
	function  Person(name) {
		this.name  =  name;
		_classCheck(this, Person)
	}
	Person.prototype.SayHello  =  function () {
		window.alert("My name is "  +  this.name  +  ".");
	};
	return  Person;
})();
var  p  =  Person()

子类会继承父类的公有属性和静态方法

es6中的写法

//es6中的写法
class  Child  extends  Person {
	constructor() {
		super()
		this.name  =  1;
	}
}
//es5中的写法
var  Clild  = (function (Person) {
//类的调用检测
	function  _classCheck(instance, constructor) {
		if (!(instance  instanceof  constructor)) {
		throw  new  Error('Class constructor Child cannot be invoked without new')
		}
	}
//子类继承父类的方法
	function  _inherins(subclass, superclass) {
		subclass.prototype  =  Object.create(superclass.prototype, { constructor: { value:  subclass } })
		Object.setPrototypeOf(subclass, superclass)
	}
	_inherins(Clild, Person)
	function  Clild() {
		let obj=Person.call(this)//子类继承私有属性
		let that=this;
		if(typeof obj=='object'){
			that=obj
		}
		that.name=1;//解决了父类是引用类型的问题
		_classCheck(this, Clild)
		return that
	}
return  Clild;
})(Person);