Anna K
Anna K

Reputation: 1774

JavaScript function in function, returning and accessing a value

Im totally new to JavaScript but my friend asked me for help. Im wondering if something like this would be possible in JS?

If the value of project is "garden"

I should get couple values for example for a name:

Garden Project

I tried that:

var myProject="garden";
ProjectNew.detectTemplate(myProject).choosenProject.name;

Im getting:

Unexpected exception 'ReferenceError: ProjectsNew is not defined

But it doesn't work. Is it possible what I described and would like to do in JS?

var ProjectNew = function() {

   function detectTemplate(project) {

      if (project=='garden'){
        var choosenProject = {
          name: "Garden Project",
          description: "sample description'",
          ansprechpartner: "Greg",
          branche: "shoping",
          partner: "'Stihl",
          technik: 'lawn mover selling'
          };
          return choosenProject;
       }
       }
        return {
               detectTemplate: detectTemplate
      }

}();

Upvotes: 0

Views: 49

Answers (1)

JLRishe
JLRishe

Reputation: 101652

Your code mostly works. There are just two parts you missed:

  1. Since you are defining ProjectNew using an assignment statement, you need to assign it before you try to use it. The error you are seeing means that it does not yet have a value when you are attempting to use it (or it is not within the scope where you are trying to use it).
  2. detectTemplate() returns the choosenProject itself, not an object with a property named choosenProject, so you need to remove that portion from your series of property accesses.

Working code:

var ProjectNew = function() {
  function detectTemplate(project) {

    if (project == 'garden') {
      var choosenProject = {
        name: "Garden Project",
        description: "sample description'",
        ansprechpartner: "Greg",
        branche: "shoping",
        partner: "'Stihl",
        technik: 'lawn mover selling'
      };
      return choosenProject;
    }
  }
  return {
    detectTemplate: detectTemplate
  }

}();
var myProject = "garden";
console.log(ProjectNew.detectTemplate(myProject).name);

Upvotes: 1

Related Questions