標籤:
<script type="text/javascript">
/**
* js實現繼承的第一種方式是基於原型鏈的方式
*/
function Parent() {
this.pv = "parent";
}
Parent.prototype.pp = "ok";
Parent.prototype.showParentValue = function() {
alert(this.pv);
}
function Child() {
this.cv = "child";
}
/**
* 如果想進行賦值之後,才進行原型鏈的設定,這樣賦值的原型對象
* 就會被重寫掉,賦值的對象就不存在在新的原型對象中
*/
// Child.prototype.showChildValue = function() {
// alert(this.cv);
// }
/**
* 讓Child的原型鏈指向Parent對象,也就等於完成了一次繼承
* 注意記憶體模型
*/
Child.prototype = new Parent();
Child.prototype.showChildValue = function() {
alert(this.cv);
}
/**
* 此時完成的對父類對象的覆蓋
*/
Child.prototype.showParentValue = function() {
alert("override parent");
}
/**
* 在使用原型鏈進行繼承一定要注意一下問題:
* 1、不能在設定了原型鏈之後,再重新為原型鏈賦值
* 2、一定要在原型鏈賦值之後才能添加或者覆蓋方法
*/
/**
* 當執行了下面這句話之後,意味著Child的原型又重寫了
* 這樣就不存在任何的繼承關係了
* 使用原型鏈需要注意的第一個問題
*/
// Child.prototype = {
// showChildValue:function() {
// alert(this.v);
// }
// }
var c = new Child();
c.showParentValue();
c.showChildValue();
alert(c.pp);
</script>
javascript學習筆記11(原型鏈)