Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

234
Views
Is there a way to create and access a method within a standard javascript function?

It's possible to create a method like this in a literal object :

https://jsfiddle.net/7q1530sp/2

let o = {
    f: function f () {
        alert("f")
    }
}
o.f();

Since function is also an object, I'd like to be able to do the same within a function I tried this but it doesn't work, is there a way ?

https://jsfiddle.net/7q1530sp/1

function o(){
    f: function f () {
        alert("f")
    }
}

o.f();
about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can create objects within a function in Javascript. Here is your code:

function o() {
  const d = {
    f: function f() {
      alert("f")
     },
   }
   d.f();
  }
 o();

Output: https://jsfiddle.net/pLjc0vbf/1/

about 4 years ago · Juan Pablo Isaza Report

0

You can define as many functions-within-functions as you like!

let f1 = function() {
  let f2 = function() {
    let f3 = function() {
      return 'functions';
    };
    return 'love ' + f3();
  };
  return 'I ' + f2();
};

console.log(f1());

If you want to define functions as properties, you could also do the following:

let f1 = function() {
  return 'I ';
};
f1.f2 = function() {
  return 'love ';
};
f1.f3 = function() {
  return 'functions';
};

console.log(f1() + f1.f2() + f1.f3());

Note that this property assignment works exactly the same way that objects work; e.g.

let f1 = function(){}; f1.someProperty = 'someValue';

vs

let o = {}; o.someProperty = 'someValue';

The assignment of properties to a function doesn't need to occur within the function body, but functions certainly could assign properties to themselves:

let f = function() {
  f.a = 'b';
  f.c = 'd';
};

Note that in this case the f.a and f.c properties wouldn't exist until you actually call the function by performing: f().

about 4 years ago · Juan Pablo Isaza Report

0

You have to define it outside of the function:

function o(){
  console.log("o");
}

o.f = function(){
  console.log("f");
}

o.f()

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!