面向对象的JS(4) 继承机制

在JavaScript中有好几种方法都可以实现继承。原型继承——使用prototype作为一种继承机制有许多优点,下面举例:
function Parent() {
var parentPrivate = "parent private data";
var that = this;
this.parentMethodForPrivate = function () {
return parentPrivate;
};
console.log("parent");
}
Parent.prototype = {
parentData: "parent data",
parentMethod: function (arg) {
return "parent method";
},
overrideMethod: function (arg) {
return arg + " overriden parent method";
}
}

function Child() {
// super constructor is not called, we have to invoke it
Parent.call(this);
console.log(this.parentData);
var that = this;
this.parentPrivate = function () {
return that.parentMethodForPrivate();
};
console.log("child");
}
//inheritance
Child.prototype = new Parent(); // parent
Child.prototype.constructor = Child;
//lets add extented functions
Child.prototype.extensionMethod = function () {
return " child’ s" + this.parentData;
};
//override inherited functions
Child.prototype.overrideMethod = function () {
//parent’s method is called
return" Invoking from child " + Parent.prototype.overrideMethod.call(this, "test");
};
var child = new Child(); // parent
// parent data
// child
console.log(child.extensionMethod()); //child’s parent data
console.log(child.parentData); //parent data
console.log(child.parentMethod()); //parent method
console.log(child.overrideMethod()); //Invoking from child test overriden parent method
console.log(child.parentPrivate()); // parent private data
console.log(child instanceof Parent); //true
console.log(child instanceof Child); //true

当访问子对象的成员时,从子对象开始找起,如果找不到则在其原型对象中搜索。如果还找不到,则在其父类对象和原型中搜索。以此类推一直搜索到Object的原型。这种层次被称之为"原型链"。下图描述了这种关系:

[img]http://dl2.iteye.com/upload/attachment/0093/8743/2b869f34-bbb9-33e3-8c3f-6a5b10602e25.jpg[/img]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值