1.对象冒充
引用
function Parent(username){ this.username = username; this.sayHello = function(){ alert("hello,"+this.username); } } function Child(username,password){ //三行重要代码 this.method = Parent; this.method(username); delete this.method; this.password = password; this.sayWorld = function(){ alert("world,"+this.password); } } var parent = new Parent("wlh"); var child = new Child("wlh_child","111111"); parent.sayHello(); child.sayHello(); child.sayWorld();
2.call方法方式:call方法是Function对象中的一个方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第二个参数开始,逐个赋值给函数中的参数。
1)call方法使用方式:
引用
function test(str,str2){ alert(this.name + "," +str + "," +str2); } var object = new Object(); object.name = "wlh"; //相当于调用了test函数 test.call(object,"wlhs");//将object赋给了this
结果:
wlh,wlhs,undefined
2)call方法继承
function Parent(username){ this.username = username; this.sayHello = function(){ alert("hello,"+this.username); } } function Child(username,password){ Parent.call(this,username); this.password = password; this.sayWorld = function(){ alert("world,"+this.password); } } var parent = new Parent("wlh"); var child = new Child("wlh_child","111111"); parent.sayHello(); child.sayHello(); child.sayWorld();
3.apply方法方式
function Parent(username){ this.username = username; this.sayHello = function(){ alert("hello,"+this.username); } } function Child(username,password){ Parent.apply(this,new Array(username)); this.password = password; this.sayWorld = function(){ alert("world,"+this.password); } } var parent = new Parent("wlh"); var child = new Child("wlh_child","111111"); parent.sayHello(); child.sayHello(); child.sayWorld();
4.原型链方式(prototype chain):
function Parent(){ } Parent.prototype.username = "wlh"; Parent.prototype.getUsername = function(){ alert(this.username); } function Child(){ } Child.prototype = new Parent(); Child.prototype.password = "111111"; Child.prototype.getPassword = function(){ alert(this.password); } var child = new Child(); child.getUsername(); child.getPassword();
缺点:无法实现参数的传递
5.混合方式(推荐使用该方式)
function Parent(username){ this.username = username; } Parent.prototype.getUsername = function(){ alert(this.username); } function Child(username,password){ Parent.call(this,username); this.password = password; } Child.prototype = new Parent(); Child.prototype.getPassword = function(){ alert(this.password); } var child = new Child("wlh","111111"); child.getUsername(); child.getPassword();