3

I am creating a library in javascript that create javascript objects.

  1. How can I write the interface of the library so that their users can create such objects both WITH and WITHOUT new? (I saw a lot of answers that propose constructors that auto-call itselfs with new if they were not invoked with new in first place but no the other way around).
  2. Can we use new with Object.create? For example: let dog = new Object.create(animal);
  3. How to provide inheritance

To illustrate with code, how do you write the functions Animal and Dog below so that the following expressions are valid:

let animal = new Animal(); // valid
let animal = Animal(); // valid also, we should return the same object
let dog = new Dog(); // valid, dog inherits/shares functions and properties from Animal.
let dog = Dog(); // valid also, same case as in previous call.

Thank you so much.

3
  • 2
    If a constructor returns an object, new will have no effect. Perhaps look into that. Example. Commented Apr 21, 2017 at 14:51
  • Chapter 3 of this book will probably be of some help. Commented Apr 21, 2017 at 14:56
  • So can I for instance directly return Object.Create? and it will work (including inheritance) with and without new? Commented Apr 21, 2017 at 17:05

1 Answer 1

3

I would do :

function Animal(name) {
  if(!(this instanceof Animal)) {
    return new Animal(name);
  }

  this.name = name;
}

Animal.prototype.walk = function() { console.log(this.name, 'is walking...'); };

function Dog(name) {
  if(!(this instanceof Dog)) {
    return new Dog(name);
  }

  this.name = name;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

var animal = Animal('John');
var other_animal = new Animal('Bob');

var dog = Dog('Blue');
var other_dog = new Dog('Brutus');

animal.walk(); // John is walking...
other_animal.walk(); // Bob is walking...

dog.walk(); // Blue is walking...
other_dog.walk(); // Brutus is walking...

console.log(dog instanceof Animal); // true
console.log(dog instanceof Dog); // true
Sign up to request clarification or add additional context in comments.

9 Comments

You have to set the constructor of Dog to Dog after Dog.prototype = Animal.prototype. And don't forget to put in some semicolons.
I think you set Animal.prototype.constructor to Dog because you didn't clone the prototype.
I'm wondering if there's a way to set name on Animal.prototype so that Dog inherits it .
@StevenLiekens I think Animal.call(this, name); in the Dog constructor (replacing this.name = name;) will do it
That still ends up assigning to this.name which is different from Dog.prototype.name. Maybe that's the correct behavior though.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.