How JavaScript---Child objects to access the parent object

Source: Internet
Author: User

In the traditional object-oriented programming language, a subclass is provided with special syntax to access the parent class, and we often need additional assistance from the parent class method in implementing the subclass method. In this case, the subclass will typically invoke the same name method in the parent class, eventually to complete the work.

JavaScript doesn't have a special syntax like this, but we can make one!

functionHer () {};her.prototype.name= ' Anna '; her.prototype.toString=function(){     var const = this. Constructor;  return const.uber? this. const.uber.toString () + ', ' + the. Name:   This . Name;functionHis () {};varF =function(){}; F.prototype=Her.prototype;his.prototype=NewF (); His.prototype.constructor=Her ; His.uber = Her.prototype; His.prototype.name= ' Jock ';functionChild (width, height) { This. width =width;  This. Height =height;}varF =function(){}; F.prototype=His.prototype;child.prototype=NewF (); Child.prototype.constructor=Child ; Child.uber = His.prototype; Child.prototype.name= ' Los '; Child.prototype.getArea=function(){    return  This. Width * This. Height;}

As we build our relationship, we introduce an Uber attribute and point it to the parent and object.

Here, we have updated the following:

1. Set the Usber property to a reference to the parent object;

2. The ToString () method has been updated;

The previous ToString () method simply returns THIS.name, and now we add an additional task to him, which is to check the This.constructor.usber property and call the ToString () method of the property if it exists.

Since This.constructor itself is a function, and This.constructo.usber is a reference to the parent prototype of the current object, when we call the ToString () method of the child entity, ToString () on its prototype chain Method will be called.

var my  = Child (+//  Anna, Jock, Los

How JavaScript---Child objects to access the parent object

Related Article

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.