关于JavaScript面向对象的一个示例
相关代码
- extend()函数:模拟类的继承
- 父类Common():提供addList()方法
- 第一个子类Input():具有aaa属性,自己的init(),change(),submit()方法和继承的addList()方法
- 第二个子类Button():具有aaa属性,自己的init(),change(),submit()方法和继承的addList()方法
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
var objectList = new Array();
function extend(Child, Parent){
var F = function(){};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
Child.uber = Parent.prototype;
}
var Common = function () {
};
Common.prototype.list = new Array();
Common.prototype.addList = function (object) {
objectList.push(object);
};
</script>
<form>
<input type="text" name="aaa" id="input">
<script type="text/javascript">
var Input = function (){
};
extend(Input, Common);
Input.prototype.aaa = 'aaa';
Input.prototype.init = function () {
this.addList(this);
}
Input.prototype.change = function () {
}
Input.prototype.submit = function () {
}
var inp = new Input();
inp.init();
</script>
<input type="button" name="bbb" value="Button" id="button">
<script type="text/javascript">
var Button = function () {
};
extend(Button, Common);
Button.prototype.aaa = 'bbb';
Button.prototype.init = function () {
this.addList(this);
}
Button.prototype.change = function () {
}
Button.prototype.submit = function () {
}
var btn = new Button();
btn.init();
for (x in objectList) {
alert(objectList[x].aaa);
}
</script>
</form>
</body>
</html>