2

I'm trying to use some function defined in a file inside a HTML script tag.

Here is the javascript file myfunction.js:

fct = function() {
};

Inside index.html I have:

<script src="./myfunction.js"></script>
<script>
  fct.some.property = function() {
  }
</script>

It says fct.some is undefined on the console. How to define some inside fct so that I can use it in oter scripts ? I don't want to use any librairies.

I tried the following but it does not work :

fct = function() {
  return {
    some: {}
  }
};
jerome
  • 2,029
  • 4
  • 38
  • 58

3 Answers3

1

I can't reproduce the error; when I test your code as-is I get

fct.some is undefined

The fix is:

fct.some = {};
fct.some.property = function() {
}

This works fine for me.

  • Is it possible to declare it this way : `var fct = function() { return { some: {} } };` – jerome Sep 05 '17 at 11:31
  • @jerome A better way is to declare it as `Object`: `var fct = { some: {} };` (unless you want `fct` to essentially be a class, and create multiple instances of it) –  Sep 05 '17 at 12:59
0

To make sure I have your question right, it looks like you are trying to use a function that you wrote in a javascript file directly in your html file, but you are having an issue with it coming back as undefined.

In testing it I found that as long as the fct function in your .js is global then it will work, but there is another problem with your example in the HTML ( but it may just be a typo because it's an example)

You put the script src for the .js file in above the in-inline js correctly, but then in the inline js script tag you say:

fct.some.property = function(){}

The problem with this is .some is not defined yet, so you can't attach a property to it yet. Try:

fct.some = {} // empty object
fct.some.property = function(){} 

EDIT: So, this works on repl.it, but it won't work in the stackoverflow snippet editor. In the snippet editor it gives me the same error as you are getting. Odd.

let fct = function() {

}
<!DOCTYPE html>
<html>

<head>
  <link href="index.css" rel="stylesheet" type="text/css" />
</head>

<body>
  <script src="index.js"></script>
  <script>
    console.log(fct)
    fct.some = {}
    fct.some.property = function() {
      return 7
    }
    console.log(fct.some.property())
  </script>

</body>

</html>
Michael Treat
  • 359
  • 1
  • 4
  • 10
0

You are correctly importing the JS file. Just check it is in head tag of html. You are getting this issue because you want to assign "property" to "some" of fct. As you have not define here what is "some". I have tried to resolve your problem by deleting "some"

index.html

<html>
<head>
<script src="myfunction.js"></script>
</head>
<script>
  fct.some = function() {
  }
</script>
<body>
</body>
</html>

myFunction.js
fct = function() {

};

Here are some links which can be useful for you adding custom properties to a function

Luke
  • 3,481
  • 6
  • 39
  • 63
Bhumika
  • 1
  • 1