【问题标题】:call two function by Inheritance in javascript在javascript中通过继承调用两个函数
【发布时间】:2015-03-11 17:30:00
【问题描述】:

我是 OOPS JavaScript 的新手。清楚。在此处查看我的 JavaScript 代码,

function a(){
    this.first = "Kar";
}
function b(){
    this.last = "Sho";
}
function c(){
    this.getName = function(){
        return this.first+this.last;
    }
}

c.prototype.u = new a();
c.prototype.v = new b();

var d = new c();

alert(d.getName());

在这里,我得到以下输出,

NaN

但我想打印 KarSho。问题出在哪里?

我知道以下方法,

b.prototype = new a();
c.prototype = new b();

其实我想要的是,在c中调用ab即可。就是这样。

【问题讨论】:

    标签: javascript oop inheritance prototype


    【解决方案1】:

    c 构造函数中同时调用ab

    function a(){
        this.first = "Kar";
    }
    function b(){
        this.last = "Sho";
    }
    function c(){
        a.call(this);
        b.call(this);
        this.getName = function(){
            return this.first+this.last;
        }
    }
    
    var d = new c();
    
    alert(d.getName());

    【讨论】:

      【解决方案2】:
      c.prototype.u = new a();
      c.prototype.v = new b();
      

      c.vc.u 原型属性上创建ab 对象的实例。

      要访问它们,您可以通过以下方式调用它们:

      function c(){
        this.getName = function(){
          return this.v.first + this.u.last;
        }
      }
      

      这不是真正的继承,而是属性的分配。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-02-23
        • 2015-04-09
        • 2013-03-30
        • 1970-01-01
        • 2012-09-20
        • 1970-01-01
        相关资源
        最近更新 更多