2012年6月20日 星期三

JavaScript class 宣告方式

在JavaScript的語法中,光是class的宣告方式就有好幾種,底下列出我所知道的宣告方式

function Person(name,year){
 //public attribute
 this.name=name;
 this.year=year;
 
 //public method
 this.getInfo(){
  return 'I am '+ this.name + 
      ',and I am ' + this.year + 'years old';
 }
}

用法
var p = new Person('Andy','18');
p.getInfo();

你也可以透過Prototype的方式宣告
function Person(name,year){
 //public property
 this.name=name;
 this.year=year;
}
//public method
//底下方法也可以宣告public property
//public method
Person.prototype.getInfo = function(){
  //public method
  return 'I am '+ this.name + 
      ',and I am ' + this.year + 'years old';
};
..
或者這樣宣告
var Person = function(name,year){
 //public attribute
 this.name=name;
 this.year=year;
};

//public method
Person.prototype.getInfo = function(){
  //public method
  return 'I am '+ this.name + 
      ',and I am ' + this.year + 'years old';
};
另一種宣告class的方法,不過這個方法我不知道怎麼宣告constructor
var Person = new Class;

//public method
Person.prototype.getInfo = function(){
  //public method
  return 'I am '+ this.name + 
      ',and I am ' + this.year + 'years old';
};

靜態方法(static method)部分,可以這樣宣告

//Person is class name
Person.find = function(id){/* ... */}


//instance method部分,也可以這樣宣告

//instance a Person object
var person = new Person('Andy',18);
person.find = function(id){/*  .... */}


下次再來介紹如何宣告物件 ....

1 則留言:

匿名 提到...

Thanks a lot for sharing this with all of us
you actually understand what you are talking approximately!
Bookmarked. Please additionally consult with my site =). We may have a hyperlink change contract
among us

Also visit my web blog - home cellulite treatment