Yakim shu Hi, 這是我擴充腦內海馬體的地方。

【練習】Object Oriented JavaScript - 01 封裝

物件導向基本觀念 01 封裝


封裝

1.首先建立一個Person物件

/*物件 Person*/
function Person(name, sex){
    this.name = name;
    this.sex = sex;
    this.print = function(){
        return this.name +" sex is "+ this.sex+"<br/>";
    }
}

2.基於Person新增兩個人物,確認人物是由Person出來

var person1 = new Person("yakim", "female");
var person2 = new Person("Jimmy", "male")

console.log(person1.print()); // "yakim sex is female"
console.log(person2.print()); // "Jimmy sex is male"
  

console.log("person1 is a Person : "+ (person1 instanceof Person));
// "person1 is a Person : true"
console.log("person2 is a Person : "+ (person2.constructor == Person));
// "person2 is a Person : true"

3.改變Person內容

/*函式 changeName*/
function changeName (person3){
    person3.sex = "male";
}

changeName(person1);
console.log(person1.name +" sex become "+ person1.sex);
// "yakim sex become male"

實例

JS Bin on jsbin.com


資料來源:
Youtube - Object Oriented JavaScript
Youtube - JavaScript 物件導向程式設計與遊戲實作
阮一峰的网络日志