js面向对象
面向对象(oop):是一种很通用的思想,并非只有编程中能用,任何事情都可以用。
特性:
1、抽象:抓住核心问题
2、封装:不考虑内部结构,只考虑功能使用
3、继承:从父类继承出一些方法和属性,继承出新的对象(多重继承,多态)
对象的组成:
1、方法:函数
2、属性:
var a =12;// 变量:自由的不属于任何人 alert(a); var arr=[1,2,3,4]// 属性:属于一个对象的 arr.a =12; alert(arr.a);
function aaa () {//函数:自由的
alert('abc');
}
arr.aa =function(){//方法:属于对象的
alert('abc');
}
1、工厂方式
工厂函数的缺点: 1、 没有new 2、函数重复,浪费资源 function creatobj (user , age) {//工厂函数 var obj =new Object(); obj.user = user; obj.age = age; obj.showuser = function(){ alert('我的名字'+this.user); } obj.showage = function(){ alert('我的年龄'+this.age); } return obj; } var obj1 = creatobj ('aa' , 10); obj1.showage(); obj1.showuser(); var obj2 = creatobj ('bb' , 20); obj2.showage(); obj2.showuser();
2、原型
原型:可以一次给一组数据加东西(类似于class);
类:模子
对象:产品(成品)
var arr =new Array(1,2,3);
Array----类;
arr-----对象;
原型是在类上面加一些方法等
用构造函数加属性,原型加方法
混合的构造函数
function Creatobj (user , age) {
this.user = user;
this.age = age;
}
Creatobj.prototype.showuser = function() {
alert('我的名字'+this.user);
};
Creatobj.prototype.showage= function(){
alert('我的年龄s'+this.age);
}
var obj1 = new Creatobj ('aa' , 10);
obj1.showage();
obj1.showuser();
var obj2 = new Creatobj ('bb' , 20);
obj2.showage();
obj2.showuser();
3、面向对象实例
面向过程的改写成用面向对象来实现tab切换
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
input{
width:50px;
height:50px;
}
input.active{
background-color:green;
}
#div1 div{
background-color:#fff;
display:none;
}
</style>
</head>
<body>
<div id="div1">
<input type="button" value="aaa" class="active">
<input type="button" value="bbb">
<input type="button" value="ccc">
<div style="display:block">aaaa</div>
<div >dddd</div>
<div >fffff</div>
</div>
<script type="text/javascript">
window.onload = function(){
new switchbtn('div1');
}
function switchbtn(id){
var _this = this;
this.odiv = document.getElementById(id);
this.ipt = this.odiv.getElementsByTagName('input');
this.seldiv=this.odiv.getElementsByTagName('div');
for(var i =0;i<this.ipt.length;i++){
this.ipt[i].index = i;
this.ipt[i].onclick = function(){
_this.clickevent(this);
}
}
}
switchbtn.prototype.clickevent = function(abtn){
for(var m =0;m< this.ipt.length;m++){
this.ipt[m].className='';
this.seldiv[m].style.display ="none";
}
abtn.className='active';
this.seldiv[abtn.index].style.display ="block";
}
</script>
</body>
</html>

浙公网安备 33010602011771号