2

How can I make this app.locals.user to be the return value instead of a function? Right now I have to run app.locals.user().name.

How can I make it so I can just run app.locals.user.name?

    app.locals.user = function(){
            if(typeof(req.session.user) != 'undefined'){
                console.log(req.session.user.name.full);
                return req.session.user;
            }else{
                return false;
            }
        };
0

3 Answers 3

2

just return whateverVariable;

Javascript isn't typed so you can't really do anything to put this in the function signature.

function foo() {
    var x = { a : 10, b : 20};
    return x;
}

var y = foo();
debug(y.a);  //prints 10
Sign up to request clarification or add additional context in comments.

1 Comment

well at the moment I am returning the function, is there a way i can make it a inline variable?
1

Well, you could use __defineGetter__ :

app.locals.__defineGetter__("user", function() {
    if(typeof(req.session.user) != 'undefined') {
        console.log(req.session.user.name.full);
        return req.session.user;
    } else {
        return false;
    }
});

Edit : __defineGetter__ seems to be deprecated, here is a better way :

Object.defineProperty(app.locals, "user", { get : function() {
    if(typeof(req.session.user) != 'undefined') {
        console.log(req.session.user.name.full);
        return req.session.user;
    } else {
        return false;
    }
});

Comments

1

You can immediately execute the function in order to store the result as a variable:

 app.locals.user = (function(){
            if(typeof(req.session.user) != 'undefined'){
                console.log(req.session.user.name.full);
                return req.session.user;
            }else{
                return false;
            }
        })();

1 Comment

@VartanArabyan, that's true, but I thought that's what you were asking for. You cannot have a variable that automatically updates itself -- if that's what you want, then make it a function and call it every time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.