面向對象編程
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;
紅色箭頭是原型鏈。注意,Student.prototype
指向的對象就是xiaoming
、xiaohong
的原型對象,這個原型對象自己還有個屬性constructor
,指向Student
函數本身。
二 原型繼承
原型鏈爲:
new PrimaryStudent() ----> PrimaryStudent.prototype ----> Student.prototype ----> Object.prototype ----> null
理解:先讓一個委託人來管理財產,之後再由兒子來管理
繼承這個動作用一個inherits()
函數封裝起來,還可以隱藏F
的定義,並簡化代碼:
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
(1)JavaScript的原型繼承實現方式就是:
- 定義新的構造函數,並在內部用call()調用希望“繼承”的構造函數,並綁定this;
- 藉助中間函數F實現原型鏈繼承,最好通過封裝的inherits函數完成;
- 繼續在新的構造函數的原型上定義新方法。
三 class繼承
繼承這個動作用一個inherits()
函數封裝起來,還可以隱藏F
的定義,並簡化代碼:
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}