上一篇文章中我们讲到了使用call可以传递this参数!
那么本篇文章将使用call方法实现继承!
代码如下:
//使用call方式实现继承!
//父函数Paren
function Paren(username){
this.username = username;
this.getUsername = function(){ alert(this.username);}
}
//子函数Child,里面调用父函数,传入this,这样在创建Child对象时,this就代表创建的对象。
function Child(username, password){
Paren.call(this, username);
this.password = password;
this.getPassword = function(){ alert(this.password);}
}
var p = new Paren("zhangsan");
var c = new Child("lisi", "123");
//定义父对象,输出username=“zhangsan”
p.getUsername();
//定义子对象,由于子函数里面使用了Paren.call(this, username); 所以实现了方法的继承!可以调用到getUsername()方法
c.getUsername();
c.getPassword();
下面的红色解释不正确(我以为是window直接调用的,但是思路是对的)