色尼玛亚洲综合影院,亚洲3atv精品一区二区三区,麻豆freexxxx性91精品,欧美在线91

js模擬類繼承小例子

復制代碼 代碼如下:
//使用原型繼承,中間使用臨時對象作為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

JavaScript技術js模擬類繼承小例子,轉載需保留來源!

鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。

主站蜘蛛池模板: 万盛区| 聂荣县| 金山区| 莱州市| 玛沁县| 遵义市| 腾冲县| 佛学| 建湖县| 体育| 扎赉特旗| 望都县| 镇巴县| 霞浦县| 嵩明县| 年辖:市辖区| 桂平市| 仙居县| 抚州市| 肥城市| 桑植县| 宽城| 高台县| 南昌市| 二连浩特市| 威信县| 海口市| 江永县| 汾西县| 云林县| 永嘉县| 平罗县| 竹溪县| 马公市| 北辰区| 建湖县| 淳安县| 平邑县| 浦北县| 濮阳市| 林州市|