Returning functions within Javascript objects

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?

7

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.

Trả lời

Email của bạn sẽ không được hiển thị công khai. Các trường bắt buộc được đánh dấu *