JS中的继承

子元素继承父元素的方法

1、继承第一种方式:对象冒充

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(); //zhangsan
child.hello(); //lisi
child.world(); //123456

2、继承第二种方式:call()方法

function Parent(username){ this.username = username;
this.hello = function(){ alert(this.username); } }
function Child(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();

3、继承的第三种方式:apply()方法

function Parent(username){ this.username = username;
this.hello = function(){ alert(this.username); } }
function Child(username,password){ Parent.call(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();
补充:function student(){ var args = arguments; teacher.call(this,args[0],args[1]);
// teacher.apply(this,arguments); }

4、继承的第四种方式:原型链方式,即子类通过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();

**5、继承的第五种方式:**混合方式即混合了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(); //zhangsan 
c.sayWorld(); //lisi

原型链继承的实例:

function Parent(hello){ this.hello = hello; }
Parent.prototype.sayHello = function(){ alert(this.hello); }
function Child(hello,world){ Parent.call(this,hello); this.world = world; }
function inherits(Child,Parent){ function F(){ }; F.prototype=Parent.prototype;
Child.prototype=new F(); Child.prototype.construct=Child; }
inherits(Child,Parent);
Child.prototype.sayWorld = function(){ alert(this.world); }
var c = new Child("zhangsan","lisi");
alert(c._proto_._proto_===Parent.prototype); //true
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值