About inherited parameters

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.