2010.6.03(2)———javascript略字ダミー引き継ぎ


2010.6.03(2)———javascript略字ダミー引き継ぎ
まず、一つの概念を理解するには、
関数オブジェクトが作成されると、関数オブジェクトは、このようなコードを実行します.新しい関数オブジェクトは、constructor属性を含み、属性値は新しい関数オブジェクトであり、このprototypeオブジェクトは継承特徴を格納する場所である.
一般的な疑似クラスの継承方式:
var Mammal = function(name){
	this.name = name;
};
Mammal.prototype.get_name = function(){
	return this.name;
}
Mammal.prototype.says = function(){
	return this.saying || "";
};

var myCat = new Cat('xiaodu');
var says = myCat.says(); //'meow'
var name = myCat.get_name(); // 'meow xiaodu meow'


//          Mammal,        
//constructor       prototype   Mammal       
var Cat = function(name){
	this.name = name;
	this.saying = 'meow';
};
//  Cat.prototype     Mammal  
Cat.prototype = new Mammal();
Cat.prototype.get_name = function(){
	return this.says() + ' ' + this.name + ' ' + this.says();
}
この引き継ぎの中に無意味なプロトタイプがあります.これらの操作を隠すことができればいいです.
前回書いたMethodの方法はまだ覚えていません.
Function.prototype.method = function(name,func){
	if(!this.prototype[name]){
		this.prototype[name] = func;
	}
	return this;
}
私たちはそれを利用してこのプロセスを簡略化します.
まずmethod法によってinheits方法を定義します.
Function.method('inherits',function(Parent){
	this.prototype = new Parent();
	return this;
});
私たちのinheitsとmethodの方法はいずれもthisに戻ります.これはカスケードのスタイルで次のようにプログラミングできます.
var Cat = function(name){
	this.name = name;
	this.saying = 'meow';
}.
inherits(Mammal).
method("get_name",function(){
	return this.says() + ' ' + this.name + ' ' + this.says();
});
このように一言で私たちのCatを作ることができます.
しかし、この方式の集積には多くの欠陥があります.プライベート環境がないと、すべての属性は公開されています.superにアクセスできない方法などです.
酔っ払いの危険は、もしコンストラクター関数を呼び出した時に、前にnewプレフィックスを追加することを忘れたら、thisは新しいオブジェクトに結合されなくなります.thisはグローバルオブジェクトに結合されます.このようにしてグローバル変数を破壊します.だから、最良の方案はnewを使用することができません.