国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

js模擬類繼承小例子

2019-11-21 00:21:06
字體:
來源:轉載
供稿:網友
復制代碼 代碼如下:

//使用原型繼承,中間使用臨時對象作為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
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 光泽县| 大荔县| 揭阳市| 永嘉县| 雷波县| 呼玛县| 尤溪县| 珲春市| 阿拉善左旗| 寿宁县| 平和县| 修水县| 綦江县| 紫云| 睢宁县| 永年县| 中西区| 大英县| 濮阳县| 延吉市| 苍南县| 禹州市| 巴塘县| 云和县| 嵊州市| 开封县| 石渠县| 金堂县| 彭水| 拉萨市| 马边| 天峨县| 内黄县| 石城县| 玛多县| 新泰市| 柳江县| 芒康县| 浏阳市| 自治县| 荔波县|