首頁 > web前端 > js教程 > 主體

js模拟类继承小例子_javascript技巧

WBOY
發布: 2016-05-16 18:22:54
原創
928 人瀏覽過
复制代码 代码如下:

//使用原型继承,中间使用临时对象作为Child的原型属性,临时对象的原型属性再指向父类的原型,
//防止所有子类和父类原型属性都指向通一个对象.
//这样当修改子类的原型属性,就不会影响其他子类和父类
function extend(Child, Parent) {
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.base = Parent.prototype;
}

function Parent(name)
{
this.aa = 123;
this.getName = function() {return name;}; //使用闭包模拟私有成员
this.setName = function(value){name=value;};
}
Parent.prototype.print = function(){alert("print!");};
Parent.prototype.hello = function()
{
alert(this.getName() + "Parent")
};

function Child(name,age)
{
Parent.apply(this, arguments);//调用父类构造函数来继承父类定义的属性
this.age = age;
}
extend(Child,Parent); //继承Parent

Child.prototype.hello = function() //重写父类hello方法
{
alert(this.getName() + "Child");

Parent.prototype.hello.apply(this,arguments); //调用父类同名方法
};
//子类方法
Child.prototype.doSomething = function(){ alert(this.age + "Child doSomething"); };

var p1 = new Child("xhan",22);

var p2 = new Child("xxx",33);

p1.hello();
p2.hello();

p1.doSomething(); //子类方法
p1.print(); //父类方法

alert(p1 instanceof Child); //true
alert(p1 instanceof Parent);//true
相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!