ITeye博客

javascript继承方式

wanglihu · 2011-12-24 15:41 · javaScript技术 · Web前端 · Markdown

1.对象冒充

[code=js] 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(); [/code]

**2.call方法方式:**call方法是Function对象中的一个方法,因此我们定义的每个函数都拥有该方法。可以通过函数名来调用call方法,call方法的第一个参数会被传递给函数中的this,从第二个参数开始,逐个赋值给函数中的参数。 1)call方法使用方式:

[code=js] function test(str,str2){ alert(this.name + "," +str + "," +str2); } var object = new Object(); object.name = "wlh"; //相当于调用了test函数 test.call(object,"wlhs");//将object赋给了this [/code]

结果: 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();

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。