js实现继承的5种方式
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(); child.hello(); child.world();
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.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();
4.原型链:
function Person(){} Person.prototype.hello = "hello"; Person.prototype.sayHello = function(){ alert(this.hello); }
function Child(){} Child.prototype = new Person();//这行的作用是:将Parent中将所有通过prototype追加的属性和方法都追加到Child,从而实现了继承 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(); c.sayWorld();