# 認識面向對象
1. 一切事物皆對象
2. 對象具有封裝和繼承性
3. 信息隱藏
## 基本面向對象
~~~
<script>
// 定義一個基本的對象
var parson = {
name:"rose",
age:25,
eat:function(){ // 對象eat方法
alert('eat');
}
};
console.log(parson);
</script>
~~~
## 函數構造器構造對象
~~~
<script>
function person(){
}
person.prototype = {
name : "rose",
age : 25,
eat : function (){
console.log("from function obj");
return true;
}
};
var oPerson = new person(); // 創建對象
console.log(oPerson.age); // 調用對象屬性
console.log(oPerson.name);
console.log(oPerson.eat()); // 調用對象方法
</script>
~~~
## 深入JavaScript面向對象
~~~
<script type="text/javascript">
function people(){
}
people.prototype.say = function (){
console.log("hello!");
}
function student(){
}
student.prototype = new people(); // 通過new對象的方式 使得student類繼承自people
var s = new student();
s.say(); // hello! 繼承自父類方法成功
student.prototype.say = function (){
console.log('stu say hello!');
}
var s = new student();
s.say(); // stu say hello! 父類方法被復寫了
</script>
~~~
那如何在子類中調用父類呢?
~~~
<script type="text/javascript">
function people(){
}
people.prototype.say = function (){
console.log("hello!");
}
function student(){
}
student.prototype = new people(); // 通過new對象的方式 使得student類繼承自people
var s = new student();
s.say(); // hello! 繼承自父類方法成功
var superSay = student.prototype.say; // 將父類的方法賦值給變量
student.prototype.say = function (){
superSay.call(this); // 調用call方法
console.log('stu say hello!');
}
var s = new student();
s.say(); // stu say hello! 父類方法被復寫了
</script>
~~~
## 另外 閉包
~~~
<script type="text/javascript">
(function(){
function people(name){ // 傳遞參數
this.name = name;
}
people.prototype.say = function (){
console.log("hello!"+ this.name);
}
window.people = people;
}());
(function(){
function student(name){ // 傳遞參數
this.name = name;
}
student.prototype = new people(); // 通過new對象的方式 使得student類繼承自people
var superSay = student.prototype.say; // 將父類的方法賦值給變量
student.prototype.say = function (){
superSay.call(this); // 調用方法
console.log('stu say hello!'+this.name);
}
window.student = student;
}());
var s = new student('rose');
s.say(); // stu say hello! 父類方法被復寫了
// 最后結果打印了 hello!rose | stu say hello!rose
</script>
~~~
- 空白目錄
- JavaScript保留字
- JS事件
- JS面向對象
- JS內置對象
- 自定義對象
- String 字符串對象
- Date 日期時間對象
- Array 數組對象
- Math 對象
- DOM對象控制HTML
- getElementsByName
- getElementsByTagName
- getAttribute 獲取元素屬性
- setAttribute 設置元素屬性
- childNodes 訪問子節點
- parentNode 訪問父節點
- createElement 創建元素節點
- createTextNode 創建文本節點
- insertBefore 插入節點
- removeChild 刪除節點
- offsetHeight 網頁高度
- scrollHeight 網頁高度
- JS瀏覽器對象
- window對象
- 計時器
- history對象
- location對象
- screen對象
- navigator對象
- 彈出窗口
- cookies