1

After coming across Douglas Crockford's views on class-free OOP, and doing away with new and this in Javascript I tried defining an object with its own variable and function, and returning it in a javascript object, as shown below:

var newObj = function (name, lang){
    var obj = {
            "name":name,
            "greeter":greeter
    };
    return obj;
};

function greeter (lang){
        switch (lang){
                case "en":return "hi";
                case "es":return "hola";
                default: return "hello";
        }
}


//and finally, use the object    
var name = "john", lang = "es";  
var obj = newObj(name, lang);

console.log(obj.name);
console.log(obj.greeter(lang));

I know this code works in NodeJS, but I wonder if it is actually a good idea to do it this way. More specifically, are there any implications/consequences to returning functions within a javascript object that I should be aware of?

  • 1
    You might have better luck on codereview.stackexchange.com – Robert Harvey Apr 14 '16 at 6:24
  • I don't see where you are using JSON in the code you posted, but to answer your question more generally: JSON doesn't support functions. It only supports true, false, null, numbers, strings, arrays, and maps. – Jörg W Mittag Apr 14 '16 at 9:37
  • My bad, I meant javascript object, as in var obj = { "name":name, "greeter":greeter }; – Yogesch Apr 14 '16 at 9:40
  • @RobertHarvey when referring other sites, it is often helpful to point that cross-posting is frowned upon – gnat Apr 14 '16 at 10:14
  • 2
    This is really a better fit here, as it's about a general software design, but just uses some example code to illustrate the general question. Code review is about making specific production code better, not about solving general design questions, and the question over there is getting comments to that effect. – Karl Bielefeldt Apr 14 '16 at 13:02
2

In JavaScript, functions are just objects. As such, there is no particular reason not to pass them around as parts of other objects. In fact, may JavaScript libraries do this, for instance, letting you pass in an object containing a success and an error callback.

As a way of doing OOP in JavaScript, that's a perfectly reasonable way of doing things, and I've worked on real production code did that. Whether it's the best way to do it is a matter of opinion.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.