Dan Heller
Dan Heller

Reputation: 594

Javascript functions with objects-like properties

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) {...}

Upvotes: 0

Views: 43

Answers (2)

KrishCdbry
KrishCdbry

Reputation: 1059

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

Upvotes: 1

Waiski
Waiski

Reputation: 9680

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

Upvotes: 3

Related Questions