5

I have javascript file called screener.js

function ScreenerPage() {

    function onScreenListChange() {
       do stuff
    };
}

from the index.html file I include the javascript file like this:

<script type="text/javascript" src="./js/screener.js"></script>

Then later in the head section of index.html I instantiate the screenerPage object like this:

<script type="text/javascript"> 
    $(document).ready(function () { 
        screenerPage = new ScreenerPage();
    }
</script> 

Then down in the body section there is a select with onchange event that calls

<select id="screenList" onchange="screenerPage.onScreenListChange()">

but the browser shows error:

Uncaught TypeError: screenerPage.onScreenListChange is not a function

What am I doing wrong?

3

2 Answers 2

1

The way javascript works is it has objects and the way of which they are created matter! Here is the way i've found that works for this kind of thing

screener.js

    var ScreenerPage = function() {
      this.onScreenListChange = function() {
        //do stuff
        console.log("test")
      }
    }

Later on

    var a = new ScreenerPage();
    a.onScreenListChange();

if you have any questions on how it works feel free to try to message me!

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

2 Comments

Thank you Jacob, that worked! I struggle with when to use these two different formats for functions.
@user3217883 No problem! If you want to learn more on that syntax I recommend the websites w3schools.com
0

The reason it does not work is that you're having a scope issue.

The function ScreenerPage is defined in the global scope, meaning it is accessible anywhere. Now inside that function you define a local function called onScreenListChange.

You are able to do that, but that function only exists within the scope of the function you defined it in.

When I look at your function, I think you want to use classes. A class is a single name that can have multiple variables / methods to do a specific task.

class ScreenerPage {
  constructor(text){
    this.onScreenListChange(text) // Call this "method" on object creation.
  }

  onScreenListChange(text) {
    console.log(text ? text : 'do stuff');
  };
}

var a = new ScreenerPage('hi'); // now watch your console log.
a.onScreenListChange();

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.