user3217883
user3217883

Reputation: 1455

how to call a javascript function within a function

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?

Upvotes: 5

Views: 111

Answers (2)

Xorifelse
Xorifelse

Reputation: 7911

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();

Upvotes: 0

Jacob Morris
Jacob Morris

Reputation: 554

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!

Upvotes: 1

Related Questions