总结出JavaScript有以下几种继承继的方法:
1.对象冒充方法,可以多承继;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
this.newMethod=A;
this.newMethod();
this.age=20;
this.getAge=function()
{
return this.age;
}
};
var bb = new B();
alert(bb.getName());2.原型链法;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
this.age=20;
this.getAge=function()
{
return this.age;
}
};
B.prototype=new A();
var bb = new B();
alert(bb.getName());3.拷贝复制法
如:
Object.extend = function(destination,source)
{
for ( pro in source )
{
destination [pro] = source [pro];
}
return destination ;
};
A = function(){};
A.prototype =
{
code:"001",
name:"whiteangell",
getCode:function()
{
return this.code;
},
getName:function()
{
return this.name
}
};
B= function(){};
B.prototype= Object.extend({
age:20,
getAge:function()
{
return this.age;
}
},A.prototype);
var bb = new B();
alert(bb.getName());4.call()方法,可以多承继;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
A.call(this);
this.age=20;
this.getAge=function()
{
return this.age;
}
};
var bb = new B();
alert(bb.getName());5.apply()方法,可以多承继;
如:
A=function()
{
this.code="001";
this.name="whiteangell";
this.getCode=function()
{
return this.code;
}
this.getName=function()
{
return this.name
}
};
B = function()
{
A.apply(this);
this.age=20;
this.getAge=function()
{
return this.age;
}
};
var bb = new B();
alert(bb.getName());
1 楼
ftuo
2008-12-12
第一个例子:有this.newMethod();
为什么要加这句话呢。不加却出错。能解释一下吗。
为什么要加这句话呢。不加却出错。能解释一下吗。
2 楼
ftuo
2008-12-12
在线啊。刚才是在JavaEye第一个帖子,呵呵。当然这是第二个。
希望给我解疑下。
希望给我解疑下。
3 楼
whiteangell
2008-12-12
this.newMethod()相当于new A()。当构造对象B的时候,调用newMethod相当于启动A的构造函数,注意这里的上下文环境中的this对象是B的实例,所以在执行A构造函数脚本时,所有A的变量和方法都会赋值给this所指的对象,即B的实例,这样子就达到B继承了A的属性方法的目的。
4 楼
xuyao
2008-12-15
lz说的太复杂,简单的说就是执行了A函数,其实js中没有对象的概念,只有函数的。之所以有个new就是为了类似java