JavaScript的继承机制




首先是父类:
  1. function ClassA(sColor) {
  2. this.color = sColor;
  3. this.sayColor = function () {
  4. alert(this.color);
  5. };
  6. }
复制代码

第一种方式:对象冒充
  1. function ClassB(sColor, sName) {
  2. this.newMethod = ClassA;  //注意这里
  3. this.newMethod(sColor);
  4. delete this.newMethod;
  5. this.name = sName;
  6. this.sayName = function () {
  7. alert(this.name);
  8. };
  9. }
复制代码

第二种方式:call()
  1. function ClassB(sColor, sName) {
  2. ClassA.call(this, sColor);
  3. this.name = sName;
  4. this.sayName = function () {
  5. alert(this.name);
  6. };
  7. }
复制代码
第三种方式:apply()
  1. function ClassB(sColor, sName) {
  2. ClassA.apply(this, arguments);
  3. this.name = sName;
  4. this.sayName = function () {
  5. alert(this.name);
  6. };
  7. }
复制代码

第四种方式:原型链(prototype)
  1. function ClassA() {
  2. }
  3. ClassA.prototype.color = "red";
  4. ClassA.prototype.sayColor = function () {
  5. alert(this.color);
  6. };
  7. function ClassB() {
  8. }
  9. ClassB.prototype = new ClassA();
  10. ClassB.prototype.name = "";
  11. ClassB.prototype.sayName = function () {
  12. alert(this.name);
  13. };
复制代码

测试方式:
  1. var objA = new ClassA();
  2. var objB = new ClassB();
  3. objA.color = "red";
  4. objB.color = "blue";
  5. objB.name = "Nicholas";
  6. objA.sayColor();
  7. objB.sayColor();
  8. objB.sayName();
复制代码
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值