小菜AS3之路

2012.2.17
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

javascript原型继承

Posted on 2012-03-01 13:51  枫雨  阅读(152)  评论(0编辑  收藏  举报

1.Call对象冒充  继承基类的构造函数的属性,方法

2.创建一个基类对象作为子类原型的原型  共享基类prototype的方法

function Polygon(size){
    this.size = size;
}
Polygon.prototype.getArea = function(){
    return 0;
}
/**矩形*/
function Rectangle(width,height){
    Polygon.call(this,4);
    this.width = width;
    this.height= height;
    
    if(typeof(Rectangle._initialize=="undefined")){
        Rectangle.prototype.getArea = function(){
            return this.width*this.height/2;
        }
        Rectangle._initialize = true;
    }
}
Rectangle.prototype = new Polygon();

区别:

为函数动态地增加属性、方法    ----->遍历属性访问
为函数prototype的属性添加方法----->实例对象可访问,子类可访问

function Sing(){
}
Sing.name = "歌";
Sing.methed = function(){
    alert('函数名可以当作对象名,进行其他操作');
}
Sing.prototype.methed = function(){
    alert('函数名可以当作对象名,进行其他操作');
}
for(var item in Sing){
    document.write("属性名:" + item + ";属性值:" + Sing[item] + "<br/>");
}
Sing['methed']();
var obj = new Sing();
obj['methed']();
/**
 * var obj = new fun();
 * 等价
 * function fun(){};
 * var obj = {};
 * fun.call(obj)
 
*/

 对象与函数结合:

obj.fun = fun;   函数作为某一对象的方法值

fun.call(obj);   将对象作为this,调用函数