ES3版類的繼承
function Parent(name) {
this.name = name
}
function Child(name) {
Parent.call(this, name)
}
function inherit(Child, Parent) {
function Prototype() {}
Prototype.prototype = Parent.prototype;
var prototype = new Prototype();
prototype.constructor = Child;
Child.prototype = prototype;
}
inherit(Child, Parent);
複製程式碼
ES5改進版類的繼承
function Parent(name) {
this.name = name
}
Parent.staticFn = function() {
console.log('ok')
}
function Child(name) {
Parent.call(this, name)
}
function inherit(Child, Parent) {
var prototype = Object.create(Parent.prototype, {
constructor: {
value: Child
}
});
prototype.constructor = Child;
Child.prototype = prototype;
}
inherit(Child, Parent);
複製程式碼
PS:問題是靜態方法無法繼承,改進:
Child.__proto__ = Parent;
Child.staticFn()
複製程式碼
ES6版類的繼承
class Parent {
constructor(name) {
this.name = name;
}
getName() {
return this.name
}
static fn() {
return 100;
}
}
class Child extends Parent {
constructor(name, age) {
super(name);
this.age = age;
}
}
複製程式碼
ES6版類的繼承的babel降級ES5版
function defineProperties(targetObject, properties) {
properties.forEach(element => {
var property = {
value: element.value,
enumerable: true,
writeable: true,
configurable: true,
}
Object.defineProperty(targetObject, element.key, property);
});
}
function _createClass(targetObject, protoProperty, staticProperty) {
if (protoProperty) {
defineProperties(targetObject.prototype, protoProperty)
}
if (staticProperty) {
defineProperties(targetObject, staticProperty)
}
}
function _classCallCheck(instance, constructor) {
if (!(instance instanceof constructor)) {
throw new Error('without new')
}
}
function _inherits(subClass, superClass) {
subClass.prototype = Object.create(superClass.prototype, {
constructor: {
value: subClass
}
})
subClass.__proto__ = superClass;
}
var Parent = function () {
function Parent() {
_classCallCheck(this, Parent);
this.name = 'papa';
}
_createClass(Parent, [{
key: 'getName',
value: function () {
return this.name
}
}], [{
key: 'fn',
value: function () {
return 100;
}
}]);
return Parent;
}();
var Child = function (Parent) {
_inherits(Child, Parent);
function Child() {
_classCallCheck(this.Child);
let that = this;
let obj = Object.getPrototypeOf(Child).call(this);
if (typeof obj === 'object') {
that = obj;
}
return that;
}
}(Parent);
複製程式碼