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

时间:2015-07-10 17:44:29

标签: javascript object inheritance

假设我在节点模块中有对象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 :(得分:0)

这样的事情应该有用 - 如果你想在JavaScript中阅读更多关于继承策略的内容,我强烈推荐Kyle Simpson找到的材料here

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!"

答案 1 :(得分: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"