JS继承

阮一峰的日志

醍醐灌顶啊有木有,大神就是大神,知识好系统!

 

 

 继承
 一、原型继承

 1 //原型链核心是__proto__
 2   function Dog(){
 3       this.bark = function(){
 4           alert("wangwang")
 5       }
 6   }
 7   function Hashiqi(){
 8   }
 9   Hashiqi.prototype = new Dog();
10  Hashiqi.prototype.constructor=Hashiqi;//强制更正构造器的指向
11 var dog1 = new Hashiqi(); 12 dog1.bark();//wangwang 13 Hashiqi.prototype.bark = function(){ alert("wuwu"); } 14 var dog2 = new Hashiqi(); 15 dog2.bark();//wuwu 16 var dog3 = new Dog(); 17 dog3.bark();//wangwang

 二、对象冒充(使父构造函数在子构造函数中运行一遍)
临时变量

function Parent(){
}
function Child(){
    this.temp = Parent;
    this.temp();
    delete this.temp;
}

call()和apply()

function Parent(){
}
function Child(){
   Parent.call(this,var1,var2...)
   //Parent.apply(this,[var1,var2...])
}

三、复制继承(把父构造函数的每个属性都复制一遍)

Object.prototype.extend = function(obj){
    for(var key in obj){
        if(this[key]==undefined){
            this[key]=obj[key];
        }
    }
}
var cat = {color:"yellow",climb:function(){alert("我会爬树");}}
var tiger = {color:"yellow and black"}
tiger.extend(cat);
tiger.climb();//我会爬树
alert(tiger.color);//yellow and black

 


 静态方法(在对象上直接添加的方法,只属于该对象)

//这是一个构造函数,也是一个对象
function Bird(){
    this.wings=2;
    this.fly= function(){
        alert("我会飞");
    }
}
//这是Bird对象的静态方法,只属于此对象
Bird.eat = function(){
   alert("吃虫子")
}

var niao = new Bird();//Bird的实例,不能访问eat()

 

posted @ 2016-08-22 20:43  tuna-  阅读(205)  评论(0编辑  收藏  举报