js編程半年,起初沒有用OOP的方式(一是因為js的class理解起來有點困難,二是覺得當(dāng)前業(yè)務(wù)沒有那么復(fù)雜,無需用OOP,三是進(jìn)度優(yōu)先,能實現(xiàn)功能就OK)。但半年后的現(xiàn)在,越來越發(fā)現(xiàn)面向過程的代碼維護起來很費勁——因為沒有封裝、繼承。故不得不緩一緩步子,硬著頭皮再次撿起js的OOP來。
讓我茅塞頓開的是 Vjeux的文章,也要感謝引路人阮一峰老師。Vjeux的文章已經(jīng)夠好,不再自己寫了——也怕寫不好。針對ECMA-262中對prototype解釋圖自己寫了相應(yīng)的代碼,發(fā)出來,幫助學(xué)習(xí)者理解:
本文中的英文copy自ECMA-262

CF is a constructor (and also an object). Five objects have been created by using new expressions: cf1, cf2, cf3, cf4, and cf5. Each of these objects contains properties named q1 and q2. The dashed lines represent the implicit prototype relationship; so, for example, cf3’s prototype is CFp. The constructor, CF, has two properties itself, named P1 and P2, which are not visible to CFp, cf1, cf2, cf3, cf4, or cf5. The property named CFP1 in CFp is shared by cf1, cf2, cf3, cf4, and cf5 (but not by CF), as are any properties found in CFp’s implicit prototype chain that are not named q1, q2, or CFP1. Notice that there is no implicit prototype link between CF and CFp.
my code(在chrome(version: 50.0.2661.102)運行通過):
function CF() {
this.q1 = 'q1';
this.q2 = 'q2';
}
var CFp = {
CFP1: 'cfp1'
};
CF.prototype = CFp;
// 一般是直接將CFp的定義賦給prototype,無需先定義變量(圖中為了說明問題,所以費勁取名)。如下:
// CF.prototype = {
// CFP1: 'cfp1'
// }
CF.P1 = 'p1'; // 實際工作中,這類屬性基本沒什么用吧?
CF.P2 = 'p2';
var cf1 = new CF();
var cf2 = new CF();
// cf3 ~ cf5相同
console.log(cf1.q1); // 'q1'
console.log(cf1.q2); // 'q2'
console.log(cf1.CFP1); // 'cfp1'
console.log('---');
console.log(cf1.P1); // undefined, because 'P1 and P2 are not visible to CFp, cf1, ...'
console.log(cf1.P2); // undefined
console.log('---');
console.log(CF.P1); // 'p1'
console.log(CF.CFP1); // undefined, because 'there is no implicit prototype link between CF and CFp'
console.log(CF.q1); // undefined
幾個關(guān)鍵定義:
constructor
function object that creates and initializes objects
NOTE The value of a constructor’s prototype property is a prototype object that is used to implement inheritance and shared properties.
prototype
object that provides shared properties for other objects
NOTE When a constructor creates an object, that object implicitly references the constructor’s prototype property for the purpose of resolving property references. The constructor’s prototype property can be referenced by the program expression constructor.prototype, and properties added to an object’s prototype are shared, through inheritance, by all objects sharing the prototype. Alternatively, a new object may be created with an explicitly specified prototype by using the Object.create built-in function.