将一个对象的原型添加到另一个对象

3

假设我有一个名为Cat的对象在一个节点模块中。我想要替换Cat函数本身而不是它的原型。换句话说,我想把一个对象的原型添加到另一个对象中。

function Cat(name, breed){
  this.name = name
  this.breed = breed
}

Cat.prototype.sayName = function(){
  console.log(this.name)
}

Cat.prototype.sayBreed = function(){
  console.log(this.breed)
}

module.export = Cat

然后我有这个文件:

var _ = require("underscore")
var inherit = require('util').inherits;
var Cat = require("./cat")

function Dog(name, breed){
  this.name = name
  this.breed = breed
}

// Tries:
// _.extend(Dog, Cat) // logs: {}
// inherit(Dog, Cat) // error: The super constructor to `inherits` must have a prototype.
// Dog.prototype.sayName = Cat.prototype.sayName // Cannot read property 'sayName' of undefined
// Dog.prototype.sayBreed = Cat.prototype.sayBreed 

var dog = new Dog("wilmer", "huskey")
console.log(dog.__proto__)

我如何将Cat的所有原型导入/扩展/继承到Dog中?

2个回答

0

类似这样的代码应该可以运行 - 如果你想了解更多关于JavaScript继承策略的内容,我强烈推荐Kyle Simpson在这里找到的资料。

function Cat(name, breed) {
  this.name  = name
  this.breed = breed
}

Cat.prototype.sayName = function() {
  console.log(this.name)
}

Cat.prototype.sayBreed = function() {
  console.log(this.breed)
};

function Dog(name, breed) {
    Cat.call(this, name, breed);
}

Dog.prototype = Object.create(Cat.prototype);

Dog.prototype.bark = function() {
    console.log('woof!');
};

var casey = new Dog("Casey", "Golden Retriever");

casey.sayName();  // => "Casey"
casey.sayBreed(); // => "Golden Retriever"
casey.bark();     // => "woof!"

0

这个应该可以工作:

 _.extend(Dog.prototype, Cat.prototype);

所以在你的代码中,你可以这样做:

var _ = require("underscore")
var Cat = require("./cat")

function Dog(name, breed){
  this.name = name
  this.breed = breed
}

_(Dog.prototype).extend(Cat.prototype);

var dog = new Dog("wilmer", "huskey");

dog.sayName();  // => "wilmer"
dog.sayBreed(); // => "huskey"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接