最简单的面向对象程序<script type="text/javascript"> var obj = new Object(); obj.qq = ‘1079161148‘; obj.name = ‘mr lan‘ obj.showName = function() { alert(‘my name =‘ + this.name) } obj.showQQ = function() { alert(‘my qq =‘ + this.qq) } obj.showName() obj.showQQ() </script>
封装重复使用的方法;<script type="text/javascript"> function createPerson(name, qq) {//构造函数 构建出一个对象; var obj = new Object(); obj.qq = qq; obj.name = name obj.showName = function() { alert(‘my name =‘ + this.name) } obj.showQQ = function() { alert(‘my qq =‘ + this.qq) } //出厂 return obj } var obj = createPerson(‘Mr Lan‘,‘1079161148‘); var obj2 = createPerson(‘Mr Li‘,‘1079161168‘); obj.showName(); obj.showQQ(); </script>
//升级------->构造函数调用加new<script type="text/javascript"> function createPerson(name, qq) { //构造函数 构建出一个对象; this.qq = qq; this.name = name this.showName = function() { alert(‘my name =‘ + this.name) } this.showQQ = function() { alert(‘my qq =‘ + this.qq) } } var obj = new createPerson(‘Mr Lan‘, ‘1079161148‘); var obj2 = new createPerson(‘Mr Li‘, ‘1079161168‘); obj.showName() obj.showQQ()
alert(obj.showName()==obj2.showName()) //false
</script>
//进阶面向对象编程<script type="text/javascript"> //混合构造函数混合方式(构造函数配合原型) function createPerson(name, qq) { //构造函数加属性 this.qq = qq; this.name = name } createPerson.prototype.showName = function(){//原型加方法 alert(‘my name =‘ + this.name) } createPerson.prototype.showQQ = function(){ alert(‘my qq =‘ + this.qq) } var obj = new createPerson(‘Mr Lan‘, ‘1079161148‘); var obj2 = new createPerson(‘Mr Li‘, ‘1079161168‘); //obj.showName() //还可以继续用不影响使用 //obj.showQQ() alert(obj.showName()==obj2.showName())//true </script>
时间: 2024-09-28 21:30:48