类的特点

1.类只能通过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中类的写法,但是这样直接用方法名调用并不会报错
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()//不报错
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中的写法
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);
05-29 00:50