如何使用JavaScript组合

时间:2011-11-26 16:45:43

标签: javascript

我有这样的事情:

dog = function () {
  this.age;
  this.name;
  this.dog1 = new dog.shepherd();
}

dog.prototype = {
  bark : function () {
    alert( (this.getName()) + " is barking." );
  },

  [3]**getName** : function () {
    return this.name;
  }
}

dog.shepherd = function () {
  this.something;
}

dog.shepherd.prototype = function () {
  guard : function () {
        alert( ([2]**parent.getName()**) + " is barking." );
  }
}

window.onload = function () {
  var n = new dog();
  [1]**n.guard()**;
}

如何从dog.speherd原型中使用原型为狗的函数?

换句话说,当执行[1]时,[2]以伪代码写入,调用[3]。

我知道这段代码不起作用;它只是帮我解释我想要的东西。

2 个答案:

答案 0 :(得分:3)

您的标题表示您想使用合成,但您的问题正文意味着继承。以下是使用合成的方法,这可能是更好的选择。牧羊人“毕竟不是”狗(反之亦然),所以继承可能不在这里。

此外,您通常不希望像您一样设置函数的整个原型;只需添加您想要的功能。按照惯例,构造函数以大写字母开头。

function Shepherd(mydog) { 
    this.dog = mydog;
}
Shepherd.prototype.guard = function () {
    alert( this.dog.getName() + " is barking." );
}

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

Dog.prototype.getName = function () {
    return this.name;
}

Dog.prototype.bark = function () {
    alert(this.getName() + " is barking." );
}

window.onload = function () {
  var someDog = new Dog(4, "Ubu");
  var someShepherd = new Shepherd(someDog);      
  someShepherd.guard();
}

jsfiddle

答案 1 :(得分:0)

我不知道你为什么需要这样的代码,但你可以试试这个:

dog = function () {
  this.age;
  this.name;
  this.dog1 = new dog.shepherd(this);

  var d = this.dog1;
  for (var i in dog.shepherd.prototype) {
    this[i] = function(){
       return this.dog1[i].apply(d, arguments);
    }
  }
}

dog.prototype = {
  bark : function () {
    alert( (this.getName()) + " is barking." );
  },

  getName : function () {
    return this.name;
  }
}

dog.shepherd = function (parent) {
  this.parent = parent;
  this.something;
}

dog.shepherd.prototype = {
  guard : function () {
        alert( (this.parent.getName()) + " is barking." );
  }
}

window.onload = function () {
  var n = new dog();
  n.guard();
}