Is this the correct way to create an Object and place a function inside of it? Every example I come across uses code that is to simple to understand and to use effectively in an actual situation. So I’m trying to figure this out by doing.
function calc() //creating an empty object named calc
{
}
var calc = new calc(); //creating a new instance of the calc object
calc.arithmetic = function maths (input)
{
var str = input;
var a=str.substr(1,1);
var b=str.substr(2,1);
var c=str.substr(3,1);
if(b == "+")
{
answerNumber = a + c;
}
else if(b == "-")
{
answerNumber = a + c;
}
else if(b == "*")
{
answerNumber = a * c;
}
else if(b == "/")
{
answerNumber = a / c;
}
}
document.getElementById("input").value=answerNumber;
document.write(calc.arithmetic(input)) //calling the method in the context of the object.
You’re overwriting calc with a fresh object containing only myArithmetic here.
You should be doing
calc.myArithmetic=function(){};instead – this adds a new property with your function as value, which is probably what you want.