javascript継承方式

3776 ワード

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オブジェクトの一つの方法です.したがって、私たちが定義した関数ごとにこの方法があります.関数名来でコール方法を呼び出すことができます.コール方法の最初のパラメータは関数のthisに渡されます.2番目のパラメータから関数のパラメータに1つずつ与えられます.
1)コールの使い方:
参照

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)コール方法引継ぎ
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.プロトタイプチェーン方式:

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();