javascript - 如何实现C类?

查看:134
本文介绍了javascript - 如何实现C类?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问 题

var A = function(name){
  this.name=name;
}

A.prototype = {
  sayName:function(){
    alert(this.name);
  }
}

var B = function(age){
  this.age = age;
}
B.prototype = {
  sayAge : function(){
    alert(this.age)
  } 
}



//function C(){};


var c = new C("white",25);

c.sayName();
c.sayAge();

解决方案

方法一

function C(name, age) {
    this.name = name;
    this.age = age;
}

C.prototype.sayName = A.prototype.sayName;
C.prototype.sayAge = B.prototype.sayAge;

方法二

function C(name, age) {
    this.a = new A(name);
    this.b = new B(age);
}

C.prototype = {
    sayName: function() {
        this.a.sayName();
    },

    sayAge: function() {
        this.b.sayAge();
    }
};

方法三

function C(name, age) {
    this.name = name;
    this.age = age;
}

C.prototype = {
    sayName: function() {
        alert(this.name);
    },
    sayAge: function() {
        alert(this.age);
    }
};

这篇关于javascript - 如何实现C类?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆