Skip to content

Instantly share code, notes, and snippets.

@FrankFan
Last active August 29, 2015 14:17
Show Gist options
  • Save FrankFan/81d976cfc8938e4a162b to your computer and use it in GitHub Desktop.
Save FrankFan/81d976cfc8938e4a162b to your computer and use it in GitHub Desktop.
js自定义继承方法
var CTOR_NAME = 'initialize';
var extend = function(child, parent) {
if (typeof parent === 'undefined') {
parent = Object;
}
child.__super__ = parent;
child.prototype.__proto__ = parent.prototype;
var currnetClass = child;
child.prototype.super = function(methodName) {
// 把 arguments 转成数组
var args = [].splice.call(arguments, 1);
currnetClass = currnetClass.__super__;
var result = currnetClass.prototype[methodName].apply(this, args);
currnetClass = child;
return result;
}
};
var Class = function(properties, parent) {
// 用 initialize 方法代替构造函数
function ctor() {
if (properties.hasOwnProperty(CTOR_NAME)) {
properties[CTOR_NAME].apply(this, arguments);
}
}
for (var key in properties) {
if (!properties.hasOwnProperty(key)) {
continue;
}
if (key === CTOR_NAME) {
continue;
}
ctor.prototype[key] = properties[key];
}
// 继承
extend(ctor, parent);
return ctor;
};
module.exports = Class;
var __hasProp = {}.hasOwnProperty;
__extends = function(child, parent) {
for (var key in parent) {
if (__hasProp.call(parent, key)) child[key] = parent[key];
}
function ctor() {
// why set the prototype's constructor to child?
this.constructor = child;
}
ctor.prototype = parent.prototype;
child.prototype = new ctor;
child.__super__ = parent.prototype;
return child;
};
// test code
var parent = { arr: [1,2,3,4,5], hello: 'haha', world: 'hehe', myobj: {name: 'chrome', age: 22}};
var child = { a: '1', b: '2'};
var res = __extends(child, parent);
console.log(res);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment