js確定原型和實例的基本關係

可以通過兩種方式實現原型和實例的關係。第一種實現方式使用instanceof操作符,只要用這個操作符來測試實例和原型鏈中出現過的構造函數,結果就會返回true。

代碼演示(原型鏈的代碼實現):

function SuperType(){ 
	this.property = true; 
}

//在SuperType函數的原型鏈上創建實例共享方法 
SuperType.prototype.getSuperValue = function(){ 
	return this.property; 
};

function SubType(){ 
	this.subProperty = false; 
}

//繼承了SuperType 
SubType.prototype = new SuperType();

SubType.prototype.getSubValue = function(){ 
	return this.subProperty; 
}

var instance = new SubType(); 
alert(instance.getSuperValue()); //true;

對上面的代碼進行測試:

alert(instance instanceof Object);		//true
alert(instance instanceof SuperType);	//true
alert(instance instanceof SubType);		//true

第二種方式是isPrototypeOf()方法。同樣,只要是原型鏈中出現過的原型,都可以說是該原型鏈所派生的實例的原型,因此isPrototypeOf()方法也會返回true。

alert(Object.prototype.isPrototypeOf(instance));	// true
alert(SuperType.prototype.isPrototypeOf(instance));	// true
alert(SubType.prototype.isPrototypeOf(instance));	// true

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章