物件導向基本觀念 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
出來
instanceof
constrcotor
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"
資料來源:
Youtube - Object Oriented JavaScript
Youtube - JavaScript 物件導向程式設計與遊戲實作
阮一峰的网络日志