1. 程式人生 > >高級面向對象

高級面向對象

基本類型 function eof true 共享 自己 name urn har

一,JS是基於原型的對象

        //最基本的面向對象寫法
	//創建構造函數
	function Aaa(){
		this.name=‘小明‘;
	}
	//構造方法
	Aaa.prototype.showName=function(){
		alert(this.name);
	}
	
	//使用
	//創建實例
	var a1=new Aaa();
	a1.showName();
	
	
	//在JS源碼中:系統對象也是基於原型的程序
	function Array(){
		this.lenglth=0;
	}
	Array.prototype.push=function(){};
	Array.prototype.sort=function(){};
	
	var arr=new Array();
	arr.push();
	arr.sort();    

二,包裝對象

/*var str=‘hello‘;

alert(typeof str);//string

str.charAt(0);
str.indexOf(‘e‘);*/

//包裝對象:基本類型都有自己對應的包裝對象,String/Number/Boolean
//var str=new String(‘hello‘);
//alert(typeof str);//object	
//String.prototype.charAt=function(){};	

var str=‘hello‘;

//調用此句時觸發的動作:基本類型會找到對應的包裝對象類型,然後包裝對象把所有的屬性和方法給基本類型,然後包裝對象消失
//str.charAt(0);

//在原型上創建的方法是共享的
String.prototype.lastValue=function(){
	return this.charAt(this.length-1);
}

alert(str.lastValue());//o

//調用此句時,在String包裝對象下創建num屬性,創建完成後包裝對象消失
str.num=10;
//此句又重新創建了num屬性
alert(str.num);//undefined

  

高級面向對象