js class

http://developer.51cto.com/art/201103/248504_all.htm

3、组合构造函数/原型方式写类 ,采用前面种方式继承

这种方式父类,子类的属性都挂在构造函数里,方法都挂在原型上

 
 
  1.  * 父类Polygon:多边形  
  2. function Polygon(sides) {  
  3.     this.sides = sides;  
  4. Polygon.prototype.setSides = function(s) {this.sides=s;}  
  5.  * Triangle 三角形  
  6.  * @param {Object} base 底  
  7.  * @param {Object} height 高  
  8. function Triangle(base,height) {  
  9.     Polygon.call(this,3);//复制父类属性给自己  
  10.     this.base = base;  
  11.     this.height = height;  
  12. Triangle.prototype = new Polygon();//复制父类方法给自己  
  13. Triangle.prototype.getArea = function(){ //最后定义自己的方法  
  14.     return this.base*this.height/2;  
  15. //new个对象  
  16. var tri = new Triangle(12,4);  
  17. console.log(tri.sides);//继承的属性  
  18. console.log(tri.setSides);//继承的方法  
  19. console.log(tri.base);//自有属性  
  20. console.log(tri.height);//自有属性  
  21. console.log(tri.getArea);//自有方法  
  22. //instanceof测试,表明正确的维护了"is a"的关系  
  23. console.log(tri instanceof Triangle);//true,表明该对象是三角形  
  24. console.log(tri instanceof Polygon);//true,表明三角形也是多边形 


//可以用json方式简化prototype的定义:

        Car.prototype =
        {
            color: "red",
            doors: 4,
            drivers: ["Tom", "Jerry",'safdad'],
            showColor: function() {
                alert(this.color);
            }
        }








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值