1。一个单独的类
class Child{
constructor(){
this.age = 9;
}
static a(){
return 1;
}
smoking(){
console.log('smoking');
}
}
let child = new Child();
conso.log(Child.a());
2。类的继承
class Parent{
constructor(){
this.name = 'parent';
}
static b(){
return 2;
}
eat(){
console.log('eat');
}
}
class Child extends Parent{
constructor(){
super();
this.age = 9;
}
static a(){
return 1;
}
smoking(){
console.log('smoking');
}
}
let child = new Child();
console.log(child);
3。实现一个类的es6的编译过程
- 第一步就是类 的调用检测
- 第二步就是创建类,实现属性构造器来定义类的公有属性和静态方法
function _classCallcheck(instance, constructor){
if(!(instance instanceof constructor)){
throw new Error('Class constructor Parent Can not be invoked without new');
}
}
function _creatClass(constructor, prototypePropertys, staticPropertys){
definePropertys(constructor.prototype, prototypePropertys);
definePropertys(constructor, staticPropertys);
}
function definePropertys(target, arr){
for(let i = 0; i < arr.length; i++){
Object.defineProperty(target, arr[i].key, {
...arr[i],
enumerable:true,
configurable:true,
writable:true,
})
}
}
let Parent = function(){
function p(){
_classCallcheck(this, p);
this.age = 9;
}
_creatClass(p,
[
{
key:'eat',
value:function(){
console.log('吃');
}
}
],
[
{
key:'b',
value:function(){
return 2;
}
}
]
)
return p;
}();
let parent = new Parent();
parent.eat();
console.log(Parent.b());
4。实现es6的类的继承的编译过程
function _classCallcheck(instance, constructor){
if(!(instance instanceof constructor)){
throw new Error('Class constructor Can not be invoked without new');
}
}
function _creatClass(constructor, prototypePropertys, staticPropertys){
definePropertys(constructor.prototype, prototypePropertys);
definePropertys(constructor, staticPropertys);
}
function definePropertys(target, arr){
for(let i = 0; i < arr.length; i++){
Object.defineProperty(target, arr[i].key, {
...arr[i],
enumerable:true,
configurable:true,
writable:true,
})
}
}
let Parent = function(){
function p(){
_classCallcheck(this, p);
this.name = 'parent';
}
_creatClass(p,
[
{
key:'eat',
value:function(){
console.log('吃');
}
}
],
[
{
key:'b',
value:function(){
return 2;
}
}
]
)
return p;
}();
function _inherits(subClass, superClass){
subClass.prototype = Object.create(subClass.prototype,{constructor:{value:subClass}});
Object.setPrototypeOf(subClass,superClass)
}
let Child = (function(Parent){
_inherits(C,Parent);
function C(){
_classCallcheck(this,C);
let obj = Parent.call(this);
let that = this;
if(typeof obj === 'object'){
that = obj;
}
that.age = 9;
return that;
}
return C;
})(Parent);
let child = new Child();
console.log(child);
console.log(Child.b());