JS继承
2017-11-05 本文已影响15人
饥人谷_米弥轮
1.基本原型链继承
<script type="text/javascript">
//animal 父类 超类
var Animal = function (name) {
this.name = name;
this.sayhello = function () {
alert("HI,我是" + this.name + ",你愿意和我做朋友吗?");
};
};
Animal.prototype.shout = function () {
alert(this.name + ",正在叫!");
};
Animal.prototype.game = function () {
alert(this.name + ",正在玩耍!");
};
var Dog = function (name) {
// this.name = name; //重写父类属性
// IE不支持Dog.prototype.__proto__ 这种继承方式,会报错
Dog.prototype.name = name; //继承父类属性
this.shout = function () //重写父类的函数
{
alert(this.name + ",正在汪汪叫!");
}
console.log(this);
};
//原型继承
Dog.prototype = new Animal();
var dog = new Dog("小黑");
dog.sayhello();
dog.shout();
dog.game();
</script>
2.封装成方法的原型链继承
<script type="text/javascript">
// 原型继承可以在Function这个对象中添加一个方法,可以方法会继承到所有的类或者函数当中,当需要的时候直接调用
Function.prototype.extends = function (superclass) {
this.prototype = new superclass();
};
//animal 父类 超类
var Animal = function (name) {
this.name = name;
this.sayhello = function () {
alert("HI,我是" + this.name + ",你愿意和我做朋友吗?");
};
};
Animal.prototype.shout = function () {
alert(this.name + ",正在叫!");
};
Animal.prototype.game = function () {
alert(this.name + ",正在玩耍!");
};
var Dog = function (name) {
this.name = name;
this.shout = function () //重写父类的函数
{
alert(this.name + ",正在汪汪叫,叫的很开心!");
};
};
Dog.extends(Animal); //调用在开头Function对象中添加的方法,实现继承
var Husky = function (name, color, sex) {
this.name = name;
this.color = color;
this.sex = sex;
this.sayhello = function () {
alert("Hello,我是一条" + this.sex + "的狗,有一个非常好听的名字,叫:“" + this.name + "”,你愿意和我做朋友吗?");
};
this.showcolor = function () {
alert(this.color);
};
/*this.shout = function()//重写父类的函数
{
alert(this.name + ",哼哼叫!");
};*/
};
Husky.extends(Dog);
var xh = new Husky("小哈", "黑白", "雄性");
xh.sayhello();
xh.shout();
xh.game();
xh.showcolor();
</script>
3.call\apply继承
<script type="text/javascript">
var Animal = function (name) {
this.name = name;
this.sayhello = function () {
alert("Hello!我是" + this.name + ",你愿意和我做朋友吗?");
};
this.shout = function () {
alert(this.name + ",正在叫!");
};
this.game = function () {
alert(this.name + ",正在玩耍!");
};
console.log(this);
};
/*Animal.prototype.shout = function()
{
alert(this.name + ",正在叫!");
};
Animal.prototype.game = function()
{
alert(this.name + ",正在玩耍!");
};*/ //无法继承通过原型链新增的方法
var Dog = function (name, color) {
//Animal.apply(this, [name]);
Animal.call(this, name);
this.color = color;
this.sayhello = function () //同样可以覆盖父类(超类)中的函数(方法)
{
alert("Hello!我是" + this.name + ",你看看我的" + this.color + "色好看吗??");
};
this.showcolor = function () //同样可以自己发展出父类中所没有的属性或函数
{
alert("我是一条" + this.color + "色的小狗狗~~");
};
};
//Dog.prototype = new Animal();
var xh = new Dog("小黑", "黑白");
xh.sayhello();
xh.showcolor();
xh.shout();
xh.game();
/*
call和apply只作用于方法(函数),这种方式继承相当于浅继承,只会继承函数当前的方法(函数),而通过prototype原型链添加的方法(函数)无法继承,也无法继承属性;call和apply函数只是实现了方法的替换,而没有对对象的属性和函数进行复制操作。
原型继承,则可以继承所有的属性和函数。
*/
</script>