2014年5月30日 星期五

[js] JavaScript的"類別"用法

一般寫Java或者是其他物件導向的程式語言時
我們使用物件中的method或是attribute如果在本身物件中找不到
就會往自己的繼承來的method或者是attribute尋找

JavaScript裡面並沒有直接繼承這樣的語法,畢竟沒有類別咩~~

JavaScript首先透過function提供類似建構式的用法,更可以用來模擬類別

用法如下,介紹留待下篇講解~

建構式用法


var Person = function(){};
var p = new Person();

增加attribute


var Person = function(_name, _age){
  this.name = _name;
  this.age = _age;
};

var p = new Person("丹丹", 18);
console.log(p.name +"("+p.age+")");

增加method


var Person = function(_name, _age){
    this.name = _name;
    this.age = _age;
    this.hi = function(){
      console.log(this.name+":hi!");
    };
};

var p = new Person("丹丹", 18);
console.log(p.name +"("+p.age+")");
p.hi();

增加private attribute跟method


var Person = function(_name, _age){
  var x = 10,
y = 15;
  var getCoord = function(){
    return "("+x+","+y+")";
  };
  this.name = _name;
  this.age = _age;
  this.moveX = function(step){
    x += step;
  };
  this.moveY = function(step){
      y += step;
  };
  this.hi = function(){
    return this.name+"在"+getCoord()+":hi!";
  };
};

var p = new Person("丹丹", 18);
p.hi();  // 丹丹在(10, 15): hi!
p.moveX(5);
p.hi();  // 丹丹在(15, 15): hi!



沒有留言:

張貼留言