当前位置:编程学习 > JAVA >>

javascript之对象学习笔记(二)--对象原型,继承

这里使用rectangle()函数作为例子
1.简单函数
 function rectangle(w,h){
this.width = w;
this.height = h;    
   }
var test = new rectangle(1,2);创建简单rectangle对象,包含width,height属性
额外定义一个计算面积的函数将test对象以参数形式传入
function getRecArea(rec){
return rec.width * rec.height; 
}
console.log( getRecArea(test) );
此时就可以简单计算任意简单矩形面积,但上述不符合面向对象编程设计思想,应该将方法也包含进 " 类 "
function rectangle(w,h){
this.width = w;
this.height = h;   
this.area = function (){return this.width * this.height}
 }
console.log( test.area())
此时已经是一个很友好的解决方案,但还不是最优化的,每创建一个rectanlge对象的时候变的只是width和height参数,而里面arec函数在每个rectanlge对象里面都一样,这让我想到java里面的继承机制,java里面继承自基类,javascript里面每个对象又有prototype对象属性(其实在创建对象后就默认初始化了该对象的prototype属性值,prototype初始化是一个对象并包含一个constructor属性,这也是每个对象为什么都有constructor的原因), 添加自prototype里的函数或属性都会成为被初始化对象的属性
 function rectangle(w,h){
this.width = w;
this.height = h;
}
rectangle.prototype.arec = function () { return this.width* this .height;} //总结:将不变的属性放在prototype里面是很好的解决方案

2.拓展内建类型
  不仅用户自定义的函数有prototype,javascript内建的String ,Date等内建类 也有prototype属性;
  实例:判断字符串是否以指定字符结尾
 String.prototype.isEndWith = function(c){
return (c == this.charAt(this.length-1))
 }
var s = " STRINGc";
console.log(s.isEend());

 

摘自:讲不出再见

补充:web前端 , JavaScript ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,