javascript中面向对象的5种写法

 <!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>js封装</title>
</head>
<body> </body>
</html>
<script type="text/javascript">
//javascript中面向对象的5种写法
//定义Circle类,拥有成员变量r,常量PI和计算面积的成员函数area() //第一种写法:比较正规的写法
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(2.0);
console.log(c.area()); //第二种写法:工厂方法
var Circle = function (){
var obj = new Object();
obj.PI = 3.14159; obj.area = function (r){
return this.PI * r * r;
}
return obj;
}
var c = new Circle();
console.log(c.area(2.0)); //第三种写法
var Circle = new Object();
Circle.PI = 3.14159;
Circle.area = function (r){
return this.PI * r * r;
}
console.log(Circle.area(2.0)); //第四种写法:JSON写法
var Circle = {
"PI":3.14159,
"area":function(r){
return this.PI * r * r;
}
}
console.log(Circle.area(2.0)); //第五种写法
var Circle = new function("this.PI = 3.14159;this.area =function(r){return r * r * PI;}");
console.log((new Circle()).area(2.0)); </script>
上一篇:从 prototype.js 深入学习 javascript 的面向对象特性


下一篇:JavaScript高级 面向对象(5)--内存逻辑图画法