Why You Don't Need OOP in JavaScript (So Much)
This post has been updated at 16/05/2013.
After I did some research on OOP in JavaScript, I realized I don't need it so much. I'm used to do pretty much everything via OOP, since it's the way how Ruby, my primary language works. But JavaScript is different.
After I did some research on OOP in JavaScript, I realized I don't need it so much. I'm used to do pretty much everything via OOP, since it's the way how Ruby, my primary language works. But JavaScript is different.
Both these languages have require function. But there is a fundamental difference how these functions work:
# ruby
require "logger"
# => true
// javascript
var sys = require("sys");
// => { print: [Function]
// , puts: [Function]
// , debug: [Function]
// , error: [Function]
// , inspect: [Function]
// , p: [Function]
// , log: [Function]
// , exec: [Function]
// , inherits: [Function]
// }
See? In Ruby require simply puts everything into one global namespace, whereas in JavaScript require() returns an object. So you don't need to have a class for encapsulation.
The second big difference is that in JavaScript functions are actually closures. In Ruby there are closures (blocks & procs & lambdas), but functions aren't closures.
// requires
var model = require("model");
// setup
var db = new model.riakClient(8098, "localhost", {debug: true});
// functions
exports.get = function get (key, successCallback, errorCallback) {
model.get(db, "projects", key, successCallback, errorCallback);
};
In Ruby you would usually create a class and have a class variable @@db, but here you can just define a local variable for the context in where you define your functions. So you don't need to have a class for sharing some data
In JavaScript I tend to use composition as a replacement for inheritance. For example on my current project, I have some models. I'm not using any ORM, just a library for talking with database of my choice. I have a model.js with common functions and then I have a file with functions for each model. Each this file simply wraps functions from model and that's it. In JavaScript it's much easier than to deal with inheritance, especially because I'd need to deal with inheritance of class methods etc and it would be just too big and heavy.
blog comments powered by Disqus