-
Notifications
You must be signed in to change notification settings - Fork 2
Patterns
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
.
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.