類和實例是大多數(shù)面向對象編程語言的基本概念轰异,不過在JS中不區(qū)分類和實例的概念蹬刷,而是通過原型(prototype)來實現(xiàn)面向對象編程桨菜。原型是指當我們想要創(chuàng)建xiaoming這個具體的學生時,我們并沒有一個Student類型可用鞋吉。那怎么辦奄毡?
var Student = {
name: 'Robot',
height: 1.2,
run: function () {
console.log(this.name + ' is running...');
}
};
var xiaoming = {
name: '小明'
};
// 把xiaoming的原型指向了對象Student
xiaoming.__proto__ = Student;
xiaoming.name; // '小明'
xiaoming.run(); // 小明 is running...
JS沒有類的概念折欠,所有對象都是實例,所謂繼承關系就是把一個對象的原型指向另一個對象而已吼过,如果你把xiaoming的原型指向其他對象:
var Bird = {
fly: function () {
console.log(this.name + ' is flying...');
}
};
xiaoming.__proto__ = Bird;
xiaoming.fly(); // 小明 is flying...
請注意锐秦,在JS中不要直接用obj.proto去改變一個對象的原型,并且低版本的IE也無法使用proto盗忱。Object.create()方法可以傳入一個原型對象酱床,并創(chuàng)建一個基于該原型的新對象,但是新對象什么屬性都沒有趟佃,因此我們可以編寫一個函數(shù)來創(chuàng)建xiaoming:
// 原型對象:
var Student = {
name: 'Robot',
height: 1.2,
run: function () {
console.log(this.name + ' is running...');
}
};
function createStudent(name) {
// 基于Student原型創(chuàng)建一個新對象:
var s = Object.create(Student);
// 初始化新對象:
s.name = name;
return s;
}
var xiaoming = createStudent('小明');
xiaoming.run(); // 小明 is running...
xiaoming.__proto__ === Student; // true
實例對象
JS可以用構造函數(shù)的方法來創(chuàng)建對象扇谣,它的用法是先定義一個構造函數(shù):
function Student(name) {
this.name = name;
this.hello = function () {
alert('Hello, ' + this.name + '!');
}
}
// 在JS中用關鍵字new調用函數(shù)返回對象:
var xiaoming = new Student('小明');
xiaoming.name; // '小明'
xiaoming.hello(); // Hello, 小明!
這里請注意昧捷,如果不寫new,這就是一個普通函數(shù)并返回undefined罐寨。但是如果寫了new靡挥,它就變成了一個構造函數(shù),它綁定的this指向新創(chuàng)建的對象并默認返回this鸯绿,也就是說不需要在最后return this跋破。用new創(chuàng)建的對象還從原型上獲得了一個constructor屬性,它指向函數(shù)Student本身:
xiaoming.constructor === Student.prototype.constructor; // true
Student.prototype.constructor === Student; // true
Object.getPrototypeOf(xiaoming) === Student.prototype; // true
xiaoming instanceof Student; // true
Student.prototype指向的對象就是xiaoming瓶蝴、xiaohong的原型對象毒返,這個原型對象有個屬性constructor指向Student函數(shù)本身,但是xiaoming舷手、xiaohong這些對象沒有prototype屬性拧簸,不過可以用proto這個非標準用法來查看,現(xiàn)在我們就認為xiaoming聚霜、xiaohong這些對象“繼承”自Student狡恬。
xiaoming.name; // '小明'
xiaohong.name; // '小紅'
xiaoming.hello; // function: Student.hello()
xiaohong.hello; // function: Student.hello()
xiaoming.hello === xiaohong.hello; // false
xiaoming和xiaohong調用的hello是一個函數(shù),但它們是兩個不同的函數(shù)蝎宇,雖然函數(shù)名稱和代碼都是相同的。要讓創(chuàng)建的對象共享一個hello函數(shù)祷安,根據(jù)對象的屬性查找原則只要把函數(shù)移動到對象原型上就可以了姥芥,也就是Student.prototype:
function Student(name) {
this.name = name;
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
如果創(chuàng)建對象時忘記寫new,在strict模式下汇鞭,this.name = name將報錯凉唐,因為this綁定為undefined,在非strict模式下霍骄,this.name = name不報錯台囱,因為this綁定為window,于是無意間創(chuàng)建了全局變量name并返回undefined读整,這個結果更糟糕簿训。為了區(qū)分普通函數(shù)和構造函數(shù),按照規(guī)定構造函數(shù)首字母應當大寫米间,而普通函數(shù)首字母小寫:
function Student(props) {
this.name = props.name || '匿名'; // 默認值為'匿名'
this.grade = props.grade || 1; // 默認值為1
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
};
function createStudent(props) {
return new Student(props || {})
}
var xiaoming = createStudent({
name: '小明'
});
xiaoming.grade; // 1
如果創(chuàng)建的對象有很多屬性强品,我們只需要傳遞需要的某些屬性,剩下的屬性可以用默認值屈糊。
原型繼承
在傳統(tǒng)的基于類和實例的語言中的榛,繼承的本質是類型的拓展,由于JS采用了原型繼承逻锐,所以不存在類夫晌。我們想要在JS中實現(xiàn)繼承可以借助于中間函數(shù)雕薪,用inherits()函數(shù)進行封裝還可以隱藏中間函數(shù)的定義,并簡化代碼:
function inherits(Child, Parent) {
var F = function () {};
F.prototype = Parent.prototype;
Child.prototype = new F();
Child.prototype.constructor = Child;
}
function Student(props) {
this.name = props.name || 'Unnamed';
}
Student.prototype.hello = function () {
alert('Hello, ' + this.name + '!');
}
function PrimaryStudent(props) {
Student.call(this, props);
this.grade = props.grade || 1;
}
// 實現(xiàn)原型繼承鏈:
inherits(PrimaryStudent, Student);
// 綁定其他方法到PrimaryStudent原型:
PrimaryStudent.prototype.getGrade = function () {
return this.grade;
};
JS的原型繼承實現(xiàn)方式如下:
- 定義新的構造函數(shù)晓淀,并在內部用call()調用希望“繼承”的構造函數(shù)所袁,并綁定this;
- 借助中間函數(shù)實現(xiàn)原型鏈繼承要糊,最好通過封裝的inherits函數(shù)完成纲熏;
- 繼續(xù)在新的構造函數(shù)的原型上定義新方法;
類繼承
我們知道JS的對象模型是基于原型實現(xiàn)的锄俄,特點是簡單局劲,但是實現(xiàn)繼承需要大量代碼。ES6引入了新的關鍵字class來定義類:
class Student {
constructor(name) {
this.name = name;
}
hello() {
alert('Hello, ' + this.name + '!');
}
}
var xiaoming = new Student('小明');
xiaoming.hello();
用class直接通過extends來實現(xiàn)繼承:
class PrimaryStudent extends Student {
constructor(name, grade) {
super(name); // 記得用super調用父類的構造方法!
this.grade = grade;
}
myGrade() {
alert('I am at grade ' + this.grade);
}
}
注意奶赠,因為不是所有的主流瀏覽器都支持ES6的class鱼填,現(xiàn)在使用還不太方便,不過可以用Babel這個工具把class代碼轉換為傳統(tǒng)的prototype代碼毅戈。