時間:2019/10/29
2.構造函數(shù)和原型
1).創(chuàng)建對象方式:new Object();對象字面量;構造函數(shù)
2). 成員:
1.靜態(tài)成員:在構造函數(shù)本身上添加的成員,只能由構造函數(shù)本身來訪問;
2.實例成員:在構造函數(shù)內(nèi)部創(chuàng)建的(通過this添加的)對象成員,只能由實例化的對象來訪問。
function Star(name, age) {
// 實例成員
this.name = name;
this.age = age;
}
Star.sex = '男'; // 靜態(tài)成員
var star1 = new Star('star1', 18);
// 訪問實例成員
star1.name;
// 訪問靜態(tài)成員
Star.sex;
3).構造函數(shù)原型 prototype
解決問題:資源空間浪費(每個實例化對象中的方法都開辟新的內(nèi)存空間)
作用:原型(對象)上實現(xiàn)方法共享
// 一般情況下,公共屬性定義到構造函數(shù)里面,公共的方法放到原型對象上
Star.prototype.sing = function() {
console.log('唱歌');
}
4).對象原型 __proto__(指向構造函數(shù)原型對象)
方法查找規(guī)則:首先先看實例化對象上是否存在該方法,如果存在則執(zhí)行這個對象上的方法;如果不存在則去構造函數(shù)原型對象prototype上查找這個方法。
// __proto__對象原型和原型對象prototype等價
star1.__proto__ === Star.prototype; // true
5).constructor 構造函數(shù)(指回構造函數(shù)本身)
Star.prototype.constructor;
star1.__proto__.constructor;
/* 輸出結果都為
function Star(name. age) {
this.name = name;
this.age = age;
}
*/
// 如果修改了原來的原型對象,且給原型對象賦值的是一個對象,則必須手動的利用constructor指回原來的構造函數(shù)
Star.prototype = {
constructor: Star,
sing: function() {
console.log('唱歌');
}
}
6).構造函數(shù)、實例、原型對象三者之間的關系

三者關系.jpg
7).原型鏈

原型鏈.jpg
對象成員查找規(guī)則:

查找規(guī)則.jpg
PS:構造函數(shù)與原型對象中的this指向的是實例對象。
8).擴展內(nèi)置對象
可以通過原型對象,對原來的內(nèi)置對象進行擴展自定義的方法。
數(shù)組和字符串內(nèi)置對象不能給原型對象覆蓋操作Array.prototype = {},只能是Array.prototype.xxx = function() {}的方式,否則會覆蓋原先原型上的方法。
9).繼承
1.借用父構造函數(shù)繼承屬性
function Father(uname, age) {
// this 指向父構造函數(shù)的對象實例
this.uname = uname;
this.age = age;
}
function Son(uname, age) {
// this 指向子構造函數(shù)的對象實例
Father.call(this, uname, age); // call()改變函數(shù)內(nèi)部this指向,繼承父屬性
}
2.借用原型對象繼承方法
Father.prototype.money = function() {
console.log(100);
}
Son.prototype = new Father();
// 如果利用對象的形式修改了原型對象,需要利用constructor指回原來的構造函數(shù)
Son.prototype.constructor = Son;