0

Is there anything wrong having javascript functions objects-like properties?

function foo(prop) { return foo[prop] }
foo.faa = 'blah';
foo.fee = 'bleh';

In my real case, I'm using as a status message:

(I couldn't paste my function here as S.O. said it was too much code, but it can be found here).

So I can use like this:

if (candidateStatus(candidate) === candidateStatus.ELECTED) {...}

3
  • 2
    IMO this is a great way for dealing with validators and Enum type checking. Commented Sep 14, 2016 at 17:19
  • 2
    Functions are also objects. Just so you know, jQuery's $ is actually a function. You can call it like $('.selector') but also hosts "static" functions like $.each and $.ajax. Commented Sep 14, 2016 at 17:22
  • You can read about object-oriented JavaScript programming at developer.mozilla.org/en-US/docs/Web/JavaScript/… if you get bored:) Commented Sep 14, 2016 at 17:22

2 Answers 2

3

Nope, there is nothing wrong with that. Functions (like almost everything else) in Javascript are objects, and can be treated as such.

Sign up to request clarification or add additional context in comments.

Comments

1

Nothing wrong this will act like function [object like] properties

function foo(prop) { return foo[prop] }
foo.faa = 'blah';
foo.fee = 'bleh';

 // Is same as 

function foo(prop) { 
   this.faa = 'blan';  
   this.fee = 'bleh';
   return foo[prop];   // or we can write foo.prop
 }  
 var newFun = new foo();
  console.log(newFun['faa']);  // blan

Case this without return statement

function foo() { 
   this.faa = 'blan';  
   this.fee = 'bleh';
 }  
 var newFun = new foo();
  console.log(newFoo.faa);  // blan

1 Comment

Sorry for the typos I am answering from the mobile App. I have updated the answer it will work now

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.