
正文
向ES6靠齐的Class.js
提示:扫一扫查出行【扫一扫了解最新限行尾号】
复制提示
写在前面
在2008年的时候,John Resig写了一 Class.js,使用的方式如下:
var Person = Class.extend({
init: function(isDancing){
this.dancing = isDancing;
},
dance: function(){
return this.dancing;
}
});
var Ninja = Person.extend({
init: function(){
this._super( false );
},
dance: function(){
// Call the inherited version of dance()
return this._super();
},
swingSword: function(){
return true;
}
});
init为构造函数,通过this._super()访问 父类同名方法 。
这种看上去很酷很方便的继承方式,居然有一个致命的缺陷。那就是:
当父类A有一个方法a,子类B也有一个方法a的时候,仅仅只有子类B中的方法a才能访问父类A中的方法a,子类B中的其他方法从此就无法访问到父类A中的方法a。虽然这种场景很少,但是不完美啊不完美!!
所以就有了今天向ES6看齐的Class.js。
ES6 class
先来看看ES6中的class继承:
Class之间可以通过extends关键字,实现继承,这比ES5的通过修改原型链实现继承,要清晰和方便很多。
class ColorPoint extends Point {}
上面代码定义了一个ColorPoint类,该类通过extends关键字,继承了Point类的所有属性和方法。但是由于没有部署任何代码,所以这两个类完全一样,等于复制了一个Point类。下面,我们在ColorPoint内部加上代码。
class ColorPoint extends Point {
constructor(x, y, color) {
super(x, y); // 等同于parent.constructor(x, y)
this.color = color;
}
toString() {
return this.color + ' ' + super.toString(); // 等同于parent.toString()
}
}
上面代码中,constructor方法和toString方法之中,都出现了super关键字,它指代父类的实例(即父类的this对象)。
上面来自ruanyifeng的es6入门:http://es6.ruanyifeng.com/#docs/class
Class.js
下面是向ES6靠齐的Class.js
//所有类的基类
var Class = function () { };
//基类增加一个extend方法
Class.extend = function (prop) {
var prototype = Object.create(this.prototype);
//把要扩展的属性复制到prototype变量上
for (var name in prop) {
//下面代码是让ctor里可以直接访问使用this._super访问父类构造函数,除了ctor的其他方法,this._super都是访问父类的实例
prototype[name] = prop[name];
}
//假的构造函数
function Class() {
//执行真正的ctor构造函数
this.ctor.apply(this, arguments);
}
Class.prototype = prototype;
Class.prototype._super = Object.create(this.prototype);
Class.prototype.constructor = Class;
//任何Class.extend的返回对象都将具备extend方法
Class.extend = arguments.callee;
return Class;
};
不多说。看注释...
所以方法(包括构造函数ctor)都是通过 this._super.方法名 去访问父类方法,
如果自身没有定义父类同名的方法,也可以直接通过 this.方法名 去访问父类的方法。
欢迎使用,玩得愉快。

![[基础]ES6编程艺术 [基础]ES6编程艺术](https://www.04ip.com/template/qe/style/noimg/19.jpg)





