【笔记】 《js权威指南》- 第9章 类和模块 - 9.7 子类

1.定义子类:

Function.prototype.extend = function(constructor, method, statics) {
	return defineSubclass(this, constructor, method, statics);
};

//复制属性(覆盖同名),不处理setter getter
function extend(o, p) {
	for (prop in p) {
		o[prop] = p[prop];
	}

	return o;
}

function inherit(p) {
	if (p == null)
		throw TypeError();
	if (Object.create)
		return Object.create(p);
	//兼容
	var t = typeof p;

	if (t !== "object" && t !== "function")
		throw TypeError();

	function f() {
	};
	f.prototype = p;
	return new f();
}

function defineSubclass(superclass, constructor, method, statics) {
	constructor.prototype = inherit(superclass.prototype);
	constructor.prototype.constructor = constructor;
	//复制方法和类属性
	if (method)
		extend(constructor.prototype, method);
	if (statics)
		extend(constructor, statics);
	return constructor;
}

//定义构造函数
function ClassA(paramA, paramB) {
	//定义实例字段
	this.propA = paramA;

	this.getParamB = function() {
		return paramB;
	};
	this.setParamB = function(value) {
		paramB = value;
	};
}

//定义实例方法
ClassA.prototype.funcA = function() {
	this.setParamB(123);
	return this.getParamB();
};

//定义类字段(常亮)
ClassA.STATIC_CONSTA = 1000;

//定义类方法
ClassA.staticFuncA = function() {
};

//定义类字段
ClassA._privateProp = 1;

var ClassB = ClassA.extend(function ClassB(paramA, paramB, paramC) {
	//super父级构造函数
	ClassA.apply(this, arguments);
	this.porpC = paramC;
}, {
	funcB: function (){return " this is funcB";},
	//覆盖函数并调用父级同名函数
	funcA: function () {
		return "this is funcA's result in ClassB: " + ClassA.prototype.funcA.apply(this, arguments);
	}
});


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值