Adding prototypes from one object to another

Let's say I have an object Cat

in a node module. I want to replace a function Cat

, not prototypes. In other words, I want to take prototypes from one object and add them to another.

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

      

Then I have this file:

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__)

      

How to import / extend / inherit all prototypes from Cat

to Dog

?

+3


source to share


2 answers


This should work:

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

      



So, in code, you can:

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"

      

0


source


Something like this should work - if you want to learn more about inheritance strategies in JavaScript, I highly recommend that Kyle Simpson find the material 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!"

      

0


source







All Articles