代码
Function.prototype.method
=
function
(name, func) {
if ( ! this .prototype[name]) {
this .prototype[name] = func;
}
return this ;
};
var extend = function (subType, superType) {
// 创建临时对象,临时对象的原型指针指向父类型原型,并让子类型原型对象指向临时对象。从而通过原型链继承父类型共享方法和属性
function F() { };
F.prototype = superType.prototype;
subType.prototype = new F();
// 重新设置子类型原型对象constuctor属性,已支持正确的instanceof操作符类查询对象的正确类型
subType.prototype.constructor = subType;
// 设置子类型base属性为父类型,方便借用构造函数继承父类型属性
subType.base = superType;
// 检查父类型原型constructor属性是否正确设置,如果没有帮它正确设置
if (superType.prototype.constructor === Object.prototype.constructor) {
superType.prototype.constructor = superType;
}
};
function Parent(name) {
this .name = name;
}
Parent.method( " sayHello " , function () {
alert( this .name);
})
.method( " method1 " , function (){})
.method( " method2 " , function (){});
function Child(name, age) {
Child.base.call( this , name);
this .age = age;
}
extend(Child, Parent);
Child.method( " sayAge " , function () {
alert( this .age);
})
var p = new Parent( " aa " );
p.sayHello();
var c = new Child( " bb " , 11 );
c.sayHello();
c.sayAge();
if ( ! this .prototype[name]) {
this .prototype[name] = func;
}
return this ;
};
var extend = function (subType, superType) {
// 创建临时对象,临时对象的原型指针指向父类型原型,并让子类型原型对象指向临时对象。从而通过原型链继承父类型共享方法和属性
function F() { };
F.prototype = superType.prototype;
subType.prototype = new F();
// 重新设置子类型原型对象constuctor属性,已支持正确的instanceof操作符类查询对象的正确类型
subType.prototype.constructor = subType;
// 设置子类型base属性为父类型,方便借用构造函数继承父类型属性
subType.base = superType;
// 检查父类型原型constructor属性是否正确设置,如果没有帮它正确设置
if (superType.prototype.constructor === Object.prototype.constructor) {
superType.prototype.constructor = superType;
}
};
function Parent(name) {
this .name = name;
}
Parent.method( " sayHello " , function () {
alert( this .name);
})
.method( " method1 " , function (){})
.method( " method2 " , function (){});
function Child(name, age) {
Child.base.call( this , name);
this .age = age;
}
extend(Child, Parent);
Child.method( " sayAge " , function () {
alert( this .age);
})
var p = new Parent( " aa " );
p.sayHello();
var c = new Child( " bb " , 11 );
c.sayHello();
c.sayAge();