Skip to content
StephanHoyer edited this page Dec 13, 2014 · 13 revisions

On this page we want to collect common patterns where you normally use non-rethink.js-stuff like prototype.

constructors

Let's start with the old way of doing JS.

// standard js

function User(name) {
  this.name = name;
}

User.prototype.greet = function(getting) {
  console.log(this.name + ' says "' + (greeting || 'hi!') + '"')
}

var john = new User('John');
john.greet('howdy!'); // logs 'John says "howdy!"' to console

So how can we do this without prototype an new.

// rethink.js

function User(name) {
  var user = {
    name: name
  }
  user.greet = function(getting) {
    console.log(user.name + ' says "' + (greeting || 'hi!') + '"')
  }
  return user;
}

var john = User('John');
john.greet('howdy!'); // logs 'John says "howdy!"' to console

Pretty straight forward, right? You can hand over the user.greet-method as is as a callback, no binding needed. Downside of this is that's it's slower than the upper version. This only kicks in, if you have a lot of items to construct. We are currently working on a more meaningful performance test. We think the performance loss is not as high in real world use cases since using the constructed instances takes greater space than constructing them.

inheritance

Again, here is the standard way of doing JS.

// standard js

function User(name) {
  this.name = name;
}

User.prototype.greet = function(getting) {
  console.log(this.name + ' says "' + (greeting || 'hi!') + '"')
}

function Pirate(name) {
  User.call(this, name);
}
Pirate.prototype = Object.create(User.prototype)

Pirate.prototype.greet = function() {
  return User.greet.call(this, 'Aye!')  
}

var john = new Pirate('John');
john.greet(); // logs 'John says "aye!"' to console

And now the version without prototype an new.

// rethink.js

function User(name) {
  var user = {
    name: name
  }
  user.greet = function(getting) {
    console.log(user.name + ' says "' + (greeting || 'hi!') + '"')
  }
  return user;
}

function Pirate(name) {
  var pirate = RethinkUser(name);
  var superGreet = pirate.greet;
  pirate.greet = function() {
    console.log(superGreet('Aye!'));
  };
  return pirate;
}

var john = Pirate('John');
john.greet(); // logs 'John says "Aye!"' to console

The readability has much improved here. Sadly the performance is also worse here but only matters when you create a lot (>1000) of items.

type-checking

Clone this wiki locally