子元素继承父元素的方法
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