2013年7月3日 星期三

JS物件的使用種類

JavaScript的物件包含了屬性(property)、方法(method)

以下是我整理的三種物件表現方式:

一、
bike = new Object();
bike.maker = '光陽';
bike.year = 2007;
bike.color = '紅色';
bike.draw = function(){document.write(this.maker + this.year + this.color);}
bike.draw();

二、
bike = {
 maker: '光陽',
 year: 2007,
 color: '紅色',
 draw: function(){document.write(this.maker + this.year + this.color);}
}
bike.draw();

三、
function bike(maker, year, color){
  this.maker = maker;
  this.year = year;
  this.color = color;
  this.draw = function(){document.write(this.maker + this.year + this.color);}
 }
 John = new bike('SYM',2008,'紅色');
 Tom = new bike('Kymco'2010,'黑色');
 John.draw();
 Tom.draw();

如果要另外在某個物件加入屬性或方法,就直接以動態增加的方式進行

拿第三個方式來舉例
John.cc = '125';
John.hello = function(){document.write('123');}
John.hello(); //但是Tom.hello無法去使用hello()這個Method


另外也可以使用prototype的方式來增加物件屬性和方法,如下:
bike.prototype.cc = 0;
bike.prototype.change_cc = function(cc){this.cc = cc;}
bike.prototype.showall = function(){document.write(this.maker + this.year + this.color + this.cc);}
John.cc = 125;
Tom.change_cc(500);
John.showall();
Tom.showall();


再舉三個範例作參考:

面積計算:
function shape(x, y){
 this.x = x;
 this.y = y;
}
shape.prototype = {
 getcoordinates: function(){
  return "(" + this.x + "," + this.y +")";
 }
};
function Rectangle(x, y, width, height){
 shape.call(this,x,y);
 this.width = width;
 this.height = height;
}
Rectangle.prototype = new shape(); //跟extends一樣的功能
Rectangle.prototype.getArea = function(){
 return this.width * this.height;
}
var obj = new Rectangle(100,200,5,10);
alert(obj.getcoordinates());
alert(obj.getArea());

裡面第五行到第九行,一般是不太建議這種寫法!!

人員類別:
function Person(name, age){
 this.name = name;
 this.age = age;
 this.tostr = function(){
  return .........
 }
}
function Student(name, age, grade){
 this.prototype = Person; //跟extends一樣的功能
 this.prototype(name, age);
 this.grade = grade;

圓面積計算:
function round(r){
 var pi = 3.14159;
 this.radius = r;
 this.diameter = 2 * r;
 function round_diameter(d){
  return d * pi;
 }
 this.circumference = round_diameter(this.diameter);
 var round_area = function(r){
  return pi * Math.pow(r, 2);
 };
 this.area = round_area(this.radius);

沒有留言:

張貼留言