1.使用对象冒充实现继承(该种实现方式可以实现多继承) 实现原理:让父类的构造函数成为子类的方法,然后调用该子类的方法,通过this关键字给所有的属性和方法赋值
第一步:新建一个临时的属性,并且指向父类所指向的对象,
第二步:执行临时属性,即执行临时属性所指向的对象函数
第三步:销毁临时属性,即此时子类就已经拥有了Parent的所有属性和方法
function Parent(username){
this.username = username;
this.hello = function(){
alert(this.username);
} }
function Child(username,password){
this.method = Parent;
this.method(username);
delete this.method;
this.password = password;
this.world = function(){ alert(this.password); } }
var parent = new Parent("zhangsan");
var child = new Child("lisi","123456");
parent.hello();
child.hello();
child.world();
继承第二种方式:call()方法方式
function Parent(username){
this.username = username;
this.hello = function(){ alert(this.username); } }
functionChild(username,password){
Parent.call(this,username);
this.password = password;
this.world = function(){ alert(this.password); } }
var parent = new Parent("zhangsan");
var child = new Child("lisi","123456");
parent.hello(); child.hello(); child.world();
继承的第三种方式:apply()方法方式 apply方法接受2个参数,
A、第一个参数与call方法的第一个参数一样,即赋值给类(即方法)中出现的this
B、第二个参数为数组类型,这个数组中的每个元素依次赋值给类(即方法)所接受的参数
function Parent(username){
this.username = username;
this.hello = function(){
alert(this.username); } }
function Child(username,password){
Parent.apply(this,new Array(username));
this.password = password;
this.world = function(){ alert(this.password); } }
var parent = new Parent("zhangsan");
var child = new Child("lisi","123456");
parent.hello(); child.hello(); child.world();
对于apply和call两者在作用上是相同的,但两者在参数上有区别的。 对于第一个参数意义都一样,但对第二个参数:apply传入的是一个参数数组,也就是将多个参数组合成为一个数组传入,而call则作为call的参数传入(从第二个参数开始)。 如 func.call(func1,var1,var2,var3) 对应的apply写法为:func.apply(func1,[var1,var2,var3]) function add(a,b) { alert(a+b); } function sub(a,b) { alert(a-b); } add.call(sub,3,1);
function add(a,b) {
alert(a+b); }
function sub(a,b) {
alert(a-b); add.call(this,3,1); }
sub(3,1);
继承的第四种方式:原型链方式,即子类通过prototype将所有在父类中通过prototype追加的属性和方法都追加到Child,从而实现了继承
function Person(){ }
Person.prototype.hello = "hello";
Person.prototype.sayHello = function(){
alert(this.hello); }
function Child(){ }
Child.prototype = new Person();
Child.prototype.world = "world";
Child.prototype.sayWorld = function(){ alert(this.world); }
var c = new Child(); c.sayHello(); c.sayWorld();
继承的第五种方式:混合方式,混合了call方式、原型链方式
function Parent(hello){
this.hello = hello; }
Parent.prototype.sayHello = function(){
alert(this.hello); }
function Child(hello,world){
Parent.call(this,hello);//将父类的属性继承过来
this.world = world;//新增一些属性 }
Child.prototype = new Parent();//将父类的方法继承过来
Child.prototype.sayWorld = function(){//新增一些方法 alert(this.world); }
var c = new Child("zhangsan","lisi"); c.sayHello(); c.sayWorld();
浙公网安备 33010602011771号