js面向对象学习总结

时间:2023-03-09 15:22:00
js面向对象学习总结

1.函数作为参数进行传递

function a(str,fun){
console.log(fun(str))
}; function up(str){
return str.toUpperCase();
};
function down(str){
return str.toLowerCase();
}; a('Hello,World !',up) //HELLO,WORLD !
a('Hello,World !',down) //hello,world !

2.面向对象常用写法

1.模式
var Circle=function(r){
this.r=r;
}
Circle.PI = 3.14159;
Circle.prototype={
area:function(){
return this.r*this.r*Circle.PI;
}
}
var obj=new Circle(1.0);
alert(obj.area()) 第1中写法扩展小实例 var show={
btn:$('.div1'),
init:function(){
var that=this;
alert(this);
this.btn.click(function(){
that.change();
alert(this);
}) },
change:function(){
this.btn.css({'background':'green'}); }
}
show.init(); 2.JSON写法 var Circle={
"PI":3.14159,
"area":function(r){
return this.PI * r * r;
}
};
alert( Circle.area(1.0) ); 3.比较正规的写法 function Circle(r) {
this.r = r;
}
Circle.PI = 3.14159;
Circle.prototype.area = function() {
return Circle.PI * this.r * this.r;
} var c = new Circle(1.0);
alert(c.area());

3.实例

<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<title>新建网页 1</title>
<mce:script type=text/javascript><!--
var person=function(name,age){//定义对象构造方法
this.name=name;
this.age=age;
}
person.prototype={ //封装方法
getName:function(){
alert(this.name);
},
getAge:function(){
alert(this.age);
}
} function test(){//声明调用
var man=new person('jack',12);
man.getName()
man.getAge()
} var test2 ={ //类似静态方法 调用直接:test2.te();即可
te:function(){
alert();
},
te1:function(){
alert();
}
}
// --></mce:script>
</head>
<body>
<input type=button onclick="test()"/>
</body>
</html>

4.混合模式

function createPerson(name,age){//构造函数加属性(属性都是不一样的所有放到属性里面写)
this.name = name;
this.age = age;
} /*createPerson.prototype.showName = function(){//原型加方法
console.log(this.name)
};
createPerson.prototype.showAge = function () {//原型加方法(方法都是一样的所以放到原型里写)
console.log(this.age);
};*/ createPerson.prototype={
showName:function(){
console.log(this.name);
},
showAge:function(){
console.log(this.age);
}
}; var person1 = new createPerson('sunny','12');
var person2 = new createPerson('rain','24');
person1.showName();//sunny
person1.showAge();//
person2.showName();//rain
person2.showAge();// console.log(person1.showName)//function(){console.log(this.name);}
console.log(person2.showName)//function(){console.log(this.name);}
console.log(person1.showName==person2.showName)//这回事同一个根函数