Rumah  >  Artikel  >  hujung hadapan web  >  浅谈JavaScript 继承机制的实现

浅谈JavaScript 继承机制的实现

高洛峰
高洛峰asal
2016-11-25 15:34:54814semak imbas

对象冒充的方法实现:

[javascript]
function Human() { //定义Human类  
    this.species = "Human"; 

function Sex(sex) {     //定义Sex类  
    this.sex = sex; 

function Chinese(name,sex) { 
    this.name = name; 
    this.newMethod1 = Human;    //对象冒充,指向Human对象  
    this.newMethod1();          //调用方法,实现继承  
    delete this.newMethod1; //删除该对象的引用,避免错误调用  
     
    this.newMethod2 = Sex;      //对象冒充,指向Sex对象  
    this.newMethod2(sex);       //调用方法,实现继承  
    delete this.newMethod2; //删除该对象的引用,避免错误调用  

var chin1 = new Chinese("小明","Male"); 
function Human() {  //定义Human类
 this.species = "Human";
}
function Sex(sex) {  //定义Sex类
 this.sex = sex;
}
function Chinese(name,sex) {
 this.name = name;
 this.newMethod1 = Human;   //对象冒充,指向Human对象
 this.newMethod1();   //调用方法,实现继承
 delete this.newMethod1; //删除该对象的引用,避免错误调用
 
 this.newMethod2 = Sex;   //对象冒充,指向Sex对象
 this.newMethod2(sex);  //调用方法,实现继承
 delete this.newMethod2; //删除该对象的引用,避免错误调用
}
var chin1 = new Chinese("小明","Male");

 

对象冒充的方法很简单易懂,原理就是利用方法的调用,在函数内实现属性的定义.

而且,对象冒充还能实现多继承.但也有不好地方.

如下:


[javascript]