您的位置:首页 > Web前端 > JavaScript

javascript模拟继承

2014-03-06 20:38 375 查看
js 本没有继承,只用js语法来实现继承效果
function Person(age, name)
{
this.name =name;
this.age = age;
}
Person.prototype.sayHi = function () {
alert("age="+this.age+",name"+this.name);
}
var p1 = new Person(12, "ff");
var p2 = new Person(21, "fffs");
alert(p1.sayHi == p2.sayHi);

function Father(name, age)
{
this.name = name;
this.age = age;
}
Father.prototype.sayHi = function () {
alert(this.name+","+this.age);
}

function Son(name,age,gender)
{
this.gender = gender;
//call调用自己本身
Father.call(this, name, age);//"继承" "父类"的成员
}
// Son.prototype = Father.prototype; //可以用父类的方法(这里有指针的问题)
Son.prototype = new Father(); //得到父类对象
Son.prototyp.fungame = function () { }; //prototype也是一个对象
var f1 = new Father("JamesZou", 29);
f1.sayHi();
var s1 = new Son("jameszou", 1, true);


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: