2016/4/23

OOP練習:實作class與methods以Javascript為例

因個人對物件導向的概念的理解真的很不好

決定開始打一些文章記錄自己的練習過程與例子

上網隨邊找了篇文章,簡單的例子與程式碼來練習

此篇參考 https://goo.gl/3IeG8I





Javascript中的方法function也可作為類別class

簡單理解為function=class

例1:創造一個叫Person的類別

function Person() { }



例2:創造Person類別的實體物件,也就是實體化

function Person() { }
var person1 = new Person();
var person2 = new Person();

person1與person2為實體化的物件object



例3:建構子Constructor

建構子通常在一般OOP語言中,以method狀態存在於class中,在物件產生那刻「馬上」被呼叫

但在Javascript中function取代了這設計

function Person() {
  alert('Person instantiated');
}

alert('Person instantiated');為建構子

例4:屬性Property

Property,想成class內部附著的變數,可使用this代表自己

當在物件外部時,可使用InstanceName.Property來使用實體物件名稱.屬性

function Person(gender) {
  this.gender = gender;
  alert('Person instantiated');
}

var person1 = new Person('Male');
var person2 = new Person('Female');

//display the person1 gender
alert('person1 is a ' + person1.gender); // person1 is a Male

為Person class增加gender Property

person1.gender=實體物件名稱.屬性=InstanceName.Property


例4:方法Methods

與 property很像,使用時,加入()引入所帶參數,在定義Methods時,需使用prototype原型

function Person(gender) {
  this.gender = gender;
  alert('Person instantiated');
}

Person.prototype.sayHello = function()
{
  alert ('hello');
};

var person1 = new Person('Male');

// call the Person sayHello method.
person1.sayHello(); // hello

為Person class增加sayHello method

我覺得這很像我所認知的OOP的封裝Encapsulation

也就是我們常在使用別人寫好的函數,我們只是呼叫使用它而已

sayHello()  就是在呼叫它   我們使用它

如理解有誤,歡迎指正!


PS...每次貼上程式碼換行都會連格式一起換下來

如案Shift+Enter可單獨換行

筆記一下

沒有留言:

張貼留言