A little problem of learning to inherit today, summarize
The layout HTML and CSS are as follows:
1 < ID= "Div1"></div>2< ID= "Div2"></div>
1 Div {2 width: 200px; 3 height: 200px; 4 background: #ccc; 5 margin: 10px; 6 }
The effect is as follows:
Define a Box1 object to achieve a click on the first div color to turn red
1 functionBox1 (ID) {2 This. OBox =document.getElementById (ID);3 This. tored ();4 }5Box1.prototype.toRed =function(){6 This. Obox.onclick =function(){7 This. Style.background = "Red";8 };9 };Ten NewBox1 ("Div1");
Define a Box2 object to inherit Box1, the color turns red when you click the second div
1 functionBox2 (ID) {2Box1.call ( This, id);3 This. Topink ();4 }5 6Box2.prototype =NewBox1 ();7Box2.prototype.constructor =Box2;8 9Box2.prototype.toPink =function(){Ten This. Obox.onclick =function(){ One This. Style.background = "Pink"; A }; - }; - NewBox2 ("Div2");
At this point, running in the browser will report an error
uncaught typeerror:cannot Set property ' onclick ' of NULL
The reason for this error is that box2.prototype = new Box1 (), when the Box1 is instantiated, it needs to pass in an ID to get the object of this ID from the document. However, implementing inheritance does not require a specific instance object.
Workaround: At the beginning of the Box1 constructor to determine whether to pass in the parameter, no argument means to inherit
1 function Box1 (ID) {2 // to determine whether to pass the argument or not to return directly 3 if (! ID) {4 return; 5 }6this . OBox = document.getElementById (ID); 7 This . tored (); 8 }
Finally complete the inheritance
About inherited parameters