JavaScript(八)

面向對象編程

JavaScript 不區分類和實例的概念,而是通過原型(prototype)來實現面向對象編程。

一 創建對象

var arr = [1, 2, 3];
其原型鏈是:
arr ----> Array.prototype ----> Object.prototype ----> null
(1)構造函數

function Student(name) {
    this.name = name;
    this.hello = function () {
        alert('Hello, ' + this.name + '!');
    }
}
var xiaoming = new Student('小明');
xiaoming.hello(); // Hello, 小明!
注意,如果不寫new,這就是一個普通函數,它返回undefined。但是,如果寫了new,它就變成了一個構造函數,它綁定的this指向新創建的對象,並默認返回this,也

就是說,不需要在最後寫return this;


protos

紅色箭頭是原型鏈。注意,Student.prototype指向的對象就是xiaomingxiaohong的原型對象,這個原型對象自己還有個屬性constructor,指向Student函數本身。

二 原型繼承

原型鏈爲:

new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null
理解:先讓一個委託人來管理財產,之後再由兒子來管理

function Student(name){
this.name = name;
this.hello = function(){
return "hello,"+this.name+"!";
}
}

//構造函數
function PrimaryStudent(props){
Student.call(this.props);
this.grade = props.grade || 1;
}

//空函數
function F(){

}
//把F的原型Student.prototype
F.prototype = Student.prototype;
//把PrimaryStudent 的原型指向一個新的F對象
PrimaryStudent.prototype = new F();

//把PrimaryStudent 原型的構造函數修復爲 PrimaryStudent
PrimaryStudent.prototype.constructor = PrimaryStudent;

//繼續在 PrimaryStudent 原型(就是new F()對象)上定義方法;
PrimaryStudent.prototype.getGrade = function(){
return this.grade;
}

js-proto-extend


繼承這個動作用一個inherits()函數封裝起來,還可以隱藏F的定義,並簡化代碼:

function inherits(Child, Parent) {
    var F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}
(1)JavaScript的原型繼承實現方式就是:

  1. 定義新的構造函數,並在內部用call()調用希望“繼承”的構造函數,並綁定this;
  2. 藉助中間函數F實現原型鏈繼承,最好通過封裝的inherits函數完成;
  3. 繼續在新的構造函數的原型上定義新方法。

三 class繼承

繼承這個動作用一個inherits()函數封裝起來,還可以隱藏F的定義,並簡化代碼:

function inherits(Child, Parent) {
    var F = function () {};
    F.prototype = Parent.prototype;
    Child.prototype = new F();
    Child.prototype.constructor = Child;
}




發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章