Skip to content

Instantly share code, notes, and snippets.

@zhoufenfens
Created March 17, 2014 15:52
Show Gist options
  • Save zhoufenfens/9601922 to your computer and use it in GitHub Desktop.
Save zhoufenfens/9601922 to your computer and use it in GitHub Desktop.
function Parent(name, age) {
this.init.apply(this, arguments);
}
Parent.prototype = {
// 通过init解决参数传递的问题
init: function (name, age) {
this.name = name;
this.age = age;
},
say: function () {
alert('Hi, 我是' + this.name + ", 我今年" + this.age + "岁。")
}
}
// 继承辅助函数
var inherit = function () {
var F = function () {};
return function (C, P) {
F.prototype = P.prototype;
C.prototype = new F();
C.prototype.constructor = C; // 注意constructor设置为子类的构造函数
C.parentClass = P.prototype; // 方便调用父对象中的方法
};
}
function Child(a, b) {
this.init.apply(this, arguments);
}
inherit(Child, Parent);
var child0 = new Child('test', '19');
child.say(); // Hi,我是test,我今年19岁
child.prototype.say = function () {
alert("error...");
};
var child1 = new Child('test2', '20');
child.say(); // Hi,我是test2,我今年20岁
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment