JavaScript OOP

There are several ways to implement OOP and inheritance.

I checked a lot and choose below one which is simple to program and easy to understand.

<script>
//prototype Chain to implement mutilple extends
function ClassA() {
	this.name = "A";
	this.displayA = function(p){return p;}
}

ClassA.prototype.testA = function(p){return p;}

function ClassB(){
	this.name = "B";
	this.displayB = function(p){return p;}
}
ClassB.prototype = new ClassA();
ClassB.constructor = ClassB;

ClassB.prototype.testB = function(p){}

function ClassC(){
}
ClassC.prototype = new ClassB();
ClassC.constructor = ClassC;

var clazzc = new ClassC();
console.log(clazzc.displayB("ClassB"));
console.log(clazzc.displayA("ClassA"));
console.log(clazzc.testA("ClassC"));
</script>

Console outputs:



Notes:

1. Properties and functions encapsulated inside the Object will be allocated for each instance;

2. Properties and functions which are created by prototype form, like function testA & testB, can only be used by the Object own instance, means it's SubObject instance cannot use util SubObject extends parent's prototype.

3. Array properties defined by prototype will be shared by all instance, so should be noticed that every push or pop activity did by one instance will impact others.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值