2012-10-14 2 views
0

저는 Object를 사용하여 계산기를 만들려고합니다. 여기 JSFiddle입니다 : http://jsfiddle.net/jNqEv/4/텍스트 상자에서 검색된 값을 사용하여 수학 계산을 수행하는 JavaScript에서 객체 만들기?

나는 계산기의 나머지했다 동안이 숫자의 계산을하기 위해이 코드를 사용했다

:

/*Computes the values inside the box and returns the answer.*/ 
function compute(form) 
{ 
    form.display.value = eval(form.display.value); 
} 

지금 내가 계산을 않는 개체를 만들 필요를 JavaScript 미리 정의 된 Object eval을 사용하는 대신

기본적으로이 개체는 ID가 "input"인 텍스트 상자의 값을 사용합니다. 값은 2 * 3, 1 + 2,5/7 등의 형식입니다. 그래서 substr을 사용하여 문자열의 두 번째 데이터를 꺼내면 곱셈, 나눗셈, 뺄셈 또는 더하기 여부를 확인할 수있었습니다. "http://www.crockford.com/javascript/private :

function calc(arithmetic) 
{ 
    this.arithmetic = arithmetic; 
}   

var myCalc = new calc(input) 
    { 
    function maths (input) 
{ 
    var str = input; 
    var a=str.substr(1,1); // example: 1+2 var a holds the 1 
    var b=str.substr(2,1); //    var b holds the "+" 
    var c=str.substr(3,1); //    var c holds the 2 
          // if the sign is equal to "+" add var a plus var b 
          // and then place them inside answerNumber. 
          // then take answerNumber and place its value 
          // inside the page element with the id "input" 
    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; 
     } 


    }  

내가 개체에 대한 다양한 웹 사이트에 독서 시도했지만 그들은 단지 전혀 도움이되지 않습니다, 여기에 내가 갔던 장소 중 일부입니다 .html " ,"http://www.w3schools.com/js/js_objects.asp "등이 있습니다. 이 일을하려고하는 것은 매우 유용하지 않은 것 같습니다. 어쩌면 당신 중 일부가 도울 수 있습니다.

<input type="button" value=" = " name="enter" onClick="compute(this.form)"> 
<input name="display" id="input" size=25> 

여기에 외부 자바 스크립트 코드 포함 내 전체 시트는 다음과 같습니다

다음은 버튼 오브젝트 기능에서 트리거에 배치 될 것입니다 텍스트 상자입니다.

HTML :

<html> 
<head> 
<title>Assignment 2</title> 
</head> 
<body> 
<div align="center"> 
<span style="font-weight:bold" size="20">Calculator</span> 
<br> 
<!-- Prints my name --> 
<form name="MyName" id="form1" style="font-weight:bold" size="20"> 
<script> 
document.write("Mallery, Cody"); 
</script> 
</form> 
<!-- Script --> 
<script src="functions.js" type="text/javascript"></script> 
<!-- The Calculator! --> 
<center><form> 
<table border=4> 
<tr> 
<td> 
<input name="display" id="input" size=25> 
<br> 
</td> 
</tr> 
<tr> 
<td> 
<input type="button" value=" 7 " onClick="addChar(this.form.display, '7')"> 
<input type="button" value=" 8 " onClick="addChar(this.form.display, '8')"> 
<input type="button" value=" 9 " onClick="addChar(this.form.display, '9')"> 
<input type="button" value=" / " onClick="addChar(this.form.display, '/')"> 
<br> 

<input type="button" value=" 4 " onClick="addChar(this.form.display, '4')"> 
<input type="button" value=" 5 " onClick="addChar(this.form.display, '5')"> 
<input type="button" value=" 6 " onClick="addChar(this.form.display, '6')"> 
<input type="button" value=" * " onClick="addChar(this.form.display, '*')"> 
<br> 

<input type="button" value=" 1 " onClick="addChar(this.form.display, '1')"> 
<input type="button" value=" 2 " onClick="addChar(this.form.display, '2')"> 
<input type="button" value=" 3 " onClick="addChar(this.form.display, '3')"> 
<input type="button" value=" - " onClick="addChar(this.form.display, '-')"> 
<br> 

<input type="button" value=" 0  " onClick="addChar(this.form.display, '0')"> 
<input type="button" value=" N " onClick="changeSign(this.form.display)"> 
<input type="button" value=" + " onClick="addChar(this.form.display, '+')"> 
<input type="button" value=" C " onClick="this.form.display.value = 0 "> 
<br> 
<input type="button" value=" L " name="L" onClick="Loop(this.form.display.value)" 
               title="If the L button is pressed, the digit present in the results box will be looped through and added up to the 'digit plus 10'.For example: After the calculator has been reset. The user can press the 1 button, then the L button 55 should be displayed in the calculator 1 + 10 = 11, therefore start with 1 and loop until less than 11 adding all of the numbers 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 = 55"> 
<input type="button" value=" = " name="enter" onClick="compute(this.form)"> 
</td> 
</tr> 
</table> 
<br> 
<!-- Calculator User Guide --> 
<span style="font-weight:bold" size="20">Instructions:</span> 
<span size="16"> 
<br>Click a number, then an action, then another number, then the '=' button. 
<br>Press 'C' when ready to start over. 
<br>The 'N' makes your previous number negative. 
<br>The 'L' button requires one number to be avalible, 
<br>It will loop through "that number" to "ten plus that number" 
<br> and add all values and display. 
<br> 
<br>For example 1+2+3+4+5+6+7+8+9+10 = 55 
</span> 
<br><br> 
<!-- Browser information --> 
<span style="font-weight:bold" size="20">Navigator:</span> 
<div id="Navigator"></div> 

<script language="javascript"> 

txt = "<p>Browser CodeName: " + navigator.appCodeName + "</p>"; 
txt+= "<p>Browser Name: " + navigator.appName + "</p>"; 
txt+= "<p>Browser Version: " + navigator.appVersion + "</p>"; 
txt+= "<p>Cookies Enabled: " + navigator.cookieEnabled + "</p>"; 
txt+= "<p>Platform: " + navigator.platform + "</p>"; 
txt+= "<p>User-agent header: " + navigator.userAgent + "</p>"; 

document.getElementById("Navigator").innerHTML=txt; 

</script> 
</form>   
</div> 
</body> 
</html> 

외부 자바 스크립트 :

/* gets the input from the keyboard OR clicking the button */ 
function addChar(input, character) 
{ 
if(input.value == null || input.value == "0") 
    input.value = character; 
else 
    input.value += character; 
} 


/*changes the sign of the number inside the input box from negative to positive.*/ 
function changeSign(input) 
{ 
if(input.value.substring(0, 1) == "-") 
    input.value = input.value.substring(1, input.value.length); 
else 
    input.value = "-" + input.value; 
} 


/*Computes the values inside the box and returns the answer.*/ 
function compute(form) 
{ 
    form.display.value = eval(form.display.value); /*The Calculator uses an Object for all calculations*/ 
}     


/* Loops the input by the value + 10 */ 
function Loop(input) 
{ 
    var num = parseInt(input) + 10; 
    var i=0; 
    var sum=0; 

    while(i < num) 
     { 
      sum=sum+i; 
      i++; 
     } 
    document.getElementById("input").value=sum; 

} 

/*Compute Arithmetic*/ 
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; 
} 

그래서 당신이 올바른 방향으로 날 지점 수있는 방법은 감사합니다.

+3

eval() !!! 사용하지 마십시오! 사용자가 입력 한 값을 가져 오는 것 같습니다. 그러지 마. 이제까지. – Yatrix

+0

나는 Eval() 함수를 대체하기 위해 Object를 생성해야한다는 것을 알고있다. 이것이 나의 질문이다. 이 계산기이기 때문에 나는 1 + 2, 3 * 4, 5/6, 3-2 등을 취할 것입니다. Eval을 사용하지 않고 내 자신의 Object를 만드는 방법을 찾아야합니다. 감사. –

+1

나는 당신이 너무 많은 것을 복잡하게한다고 생각한다 ... – elclanrs

답변

1

왜 여기에 개체가 필요하다고 생각하는지 모르겠습니다. 그냥 함수에 넣으십시오 - 이미 maths 함수가 있어야합니다. 이 코드는 구문 오류 일뿐입니다.

일반적으로 var myCalc = new calc(input);calc 생성자의 인스턴스를 만듭니다. 그 뒤에는 함수 본문이 와야합니다. 또한,로가

function calc() {} 
var calc = new calc(); 

을하고 당신은 단지 그것의 인스턴스가 calc 기능을 덮어 쓰기 - 아주 이상한.

함수의 네임 스페이스를 지정하려는 경우 (즉, 속성으로 개체에 넣는 것이 좋은 생각 인 경우) 간단한 Object 리터럴을 사용해야합니다. 여러 인스턴스를 생성하는 생성자 함수가 필요하지 않으므로 하나만 있으면됩니다.

var calc = { 
    arithmetic: function maths (input) { … } 
}; 
// then call 
calc.arithmetic("1+3"); 
// which sets the input field to "4" 
+0

글쎄, 내가 목표물을 필요로하는 이유는 그것이 임무이기 때문에 나는 티를 만드는 방향을 따라야한다. 정보를 가져 주셔서 감사합니다! 도움이되었습니다. –

+0

나는이 일을하는 이유가 대상에 대해 배우는 것이라고 말할 수 있다고 생각한다. –

관련 문제