JS之面向对象

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS之面向对象相关的知识,希望对你有一定的参考价值。

用面向对象方法做一个计算器:

html代码:

<style type="text/css">
table{
margin: 0 auto;
text-align: center;
}
input{
width: 100px;
height: 80px;
font-size: 60px;
}
#sum{
width: 480px;
}

</style>

<body>
<table width="500" height="600" border="1" cellpadding="0" cellspacing="2">
<tr >
<td colspan="4">
<input type="text" id="sum"/>
</td>

</tr>
<tr >
<td><input type="button" value="1" id="num1" name="num"/></td>
<td><input type="button" value="2" id="num2" name="num"/></td>
<td><input type="button" value="3" id="num3" name="num"/></td>
<td><input type="button" value="+" id="fuhao1" name="fuhao"/></td>


</tr>
<tr >
<td><input type="button" value="4" id="num4" name="num"/></td>
<td><input type="button" value="5" id="num5" name="num"/></td>
<td><input type="button" value="6" id="num6" name="num"/></td>
<td><input type="button" value="-" id="fuhao2" name="fuhao"/></td>

</tr>
<tr >
<td><input type="button" value="7" id="num7" name="num"/></td>
<td><input type="button" value="8" id="num8" name="num"/></td>
<td><input type="button" value="9" id="num9" name="num"/></td>
<td><input type="button" value="*" id="fuhao3" name="fuhao"/></td>

</tr>
<tr height="100">

<td> <input type="button" value="0" id="num0" name="num"/></td>
<td> <input type="button" value="." id="num." name="num"/></td>
<td> <input type="button" value="=" id="dengyu" name="dengyu"/></td>
<td> <input type="button" value="/" id="fuhao4" name="fuhao"/></td>

</tr>
</table>
</body>

<script src="js/counter.js" type="text/javascript" charset="utf-8"></script>

script代码:

var counters = {
num1: 0,
fuhao: "",
sum: document.getElementById("sum"),
getnum: function(num) {
this.sum.value += num;
},
getfuhao: function(fuhao) {
this.num1 = this.sum.value;
this.fuhao = fuhao;
this.sum.value = "";

},
getvalue: function() {
this.sum.value=eval(this.num1+this.fuhao+this.sum.value);

}
}

//点击数字,显示数字
var objnum = document.getElementsByName(‘num‘);
for(var i = 0; i < objnum.length; i++) {
objnum.item(i).onclick = function() {
//alert(this.value);
counters.getnum(this.value);
}
}
//点击符号,显示符号
var objfuhao = document.getElementsByName(‘fuhao‘);
for(var j = 0; j < objfuhao.length; j++) {
objfuhao.item(j).onclick = function() {
counters.getfuhao(this.value);
//alert("aa");
}
}
//点击等号,显示结果
var objvalue = document.getElementById(‘dengyu‘);
objvalue.onclick=function(){
counters.getvalue();
//alert(‘aa‘);
}

 
























































































以上是关于JS之面向对象的主要内容,如果未能解决你的问题,请参考以下文章

浅谈JS面向对象之创建对象

JS 面向对象之对象的创建

前端 之 JavaScript : JS的面向对象; 定时器; BOM

JS面向对象之创建对象

JS之面向对象

js面向对象之原型链