2014年5月30日 星期五

[js] 繼承

接下來的主題是繼承

繼承的目的是為了程式的重用

而當我們使用JavaScript並且透過new關鍵字和function來建立類別時

其實物件裡面的attribute都是被獨立建立起來的 (物件裡面的method也算是attribute的一種)

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

  var p1 = new Person("小明", 18);
  var p2 = new Person("花花", 15);
  p1.hi();
  p2.hi();
  console.log(p1.hi == p2.hi); //false

實際上要真正的共用同一個function會需要引入prototype的概念

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

  Person.prototype.hi = function(){
    console.log(this.name +" say: hi!");
  };

  var p1 = new Person("小明", 18);
  var p2 = new Person("花花", 15);
  p1.hi();
  p2.hi();
  console.log(p1.hi == p2.hi); //true

談到prototype雖然從共用講起

但是特別該注意的是p1.hi 與 p2.hi其實並沒有直接bind在物件上面

而可以對應得到method是因為object在進行attribute的存取時的原則!!!













沒有留言:

張貼留言