js編程半年咕宿,起初沒有用OOP的方式(一是因?yàn)閖s的class理解起來有點(diǎn)困難溢豆,二是覺得當(dāng)前業(yè)務(wù)沒有那么復(fù)雜蜒简,無需用OOP,三是進(jìn)度優(yōu)先漩仙,能實(shí)現(xiàn)功能就OK)搓茬。但半年后的現(xiàn)在,越來越發(fā)現(xiàn)面向過程的代碼維護(hù)起來很費(fèi)勁——因?yàn)闆]有封裝队他、繼承卷仑。故不得不緩一緩步子,硬著頭皮再次撿起js的OOP來麸折。
讓我茅塞頓開的是 Vjeux的文章锡凝,也要感謝引路人阮一峰老師。Vjeux的文章已經(jīng)夠好垢啼,不再自己寫了——也怕寫不好窜锯。針對(duì)ECMA-262中對(duì)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)運(yùn)行通過):
function CF() {
this.q1 = 'q1';
this.q2 = 'q2';
}
var CFp = {
CFP1: 'cfp1'
};
CF.prototype = CFp;
// 一般是直接將CFp的定義賦給prototype锚扎,無需先定義變量(圖中為了說明問題捌浩,所以費(fèi)勁取名)。如下:
// CF.prototype = {
// CFP1: 'cfp1'
// }
CF.P1 = 'p1'; // 實(shí)際工作中工秩,這類屬性基本沒什么用吧尸饺?
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
幾個(gè)關(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.