简体   繁体   中英

Accessing global(javascript) variables in a private function

I'm currently working on a calculator for learning purposes and everything works, in a way, but not in the way I'd want it to.

Here's the adding up part of the code:

HTML:

<input type="number" id="int1" />
<input type="number" id="int2" />
<input type="button" onClick="sumOf();" />
<div id="result"></div>  // To display the result

JS:

var int1 = document.getElementById("int1").value;
var int1 = document.getElementById("int2").value;
var result = document.getElementById("result");

function sumOf(int1, int2) {
  result.innerHTML = parseFloat(int1) + parseFloat(int2);
}

The way it is right now, if I call the function via the onClick event it will result in NaN. Checking the type of the int's results in 'undefined'. So I put the variables inside the function and it works fine because now the function can reach them.

My question is how can I give access to the variables outside of the function? I tried creating an object, but then I had problems referring to the right function inside the object in the onClick event, I tried "objectName.functionInsideTheObject();". The result was it didn't work.

How can I make this work? New functions will be added for other calculations and it's tedious to copy paste the variables all the time.

EDIT:

My problem has something to do with ".value" in the variable declaration. If I declare a variable as such:

var int1 = document.getElementById("int1");  // Not getting the value directly
var int2 = document.getElementById("int2");

And then reference to the value of the variable inside the function like this:

function sumOf() {
  result.innerHTML = parseFloat(int1.value) + parseFloat(int2.value);
}

It works fine. I don't know why .value doesn't work in global scope. Still not perfect, but less tedious.

I believe that if you create it like this:

int1 = document.getElementById("int1").value;

without the var it's then a global.

The way you declared the variables is Right.

And these variables are NaN as you are agaian padding them as Arguments in your function

function sumOf(int1, int2) {
  result.innerHTML = parseFloat(int1) + parseFloat(int2);
}

you should call the function like

function sumOf() {
  result.innerHTML = parseFloat(int1) + parseFloat(int2);
}

But I think will be better if you declare your function like

function sumOf() {
  var int1 = document.getElementById("int1").value;
  var int1 = document.getElementById("int2").value;
  var result = document.getElementById("result");

  result.innerHTML = parseFloat(int1) + parseFloat(int2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM