[JavaScript secret garden] object 2 :? Prototype

Source: Internet
Author: User
JavaScript does not contain traditional class inheritance models, but uses prototypal prototype models.

JavaScript does not contain the traditional class inheritance model, but uses the prototypal prototype model.

Although this is often mentioned as a disadvantage of JavaScript, prototype-based inheritance models are more powerful than traditional class inheritance models. It is easy to implement the traditional class inheritance model, but it is much more difficult to implement prototype inheritance in JavaScript. (It is for example fairly trivial to build a classic model on top of it, while the other way around is a far more difficult task .)

Since JavaScript is the only language widely used based on prototype inheritance, it takes some time to understand the differences between the two inheritance modes.

The first difference is that JavaScript uses the Inheritance Method of prototype chain.

Function Foo () {this. value = 42;} Foo. prototype = {method: function () {}}; function Bar () {}// set the prototype attribute of Bar to the Instance Object Bar of Foo. prototype = new Foo (); Bar. prototype. foo = 'Hello NowaMagic '; // modify Bar. prototype. constructor is the Bar itself. prototype. constructor = Bar; var test = new Bar () // create a new instance of Bar

Simply using Bar. prototype = Foo. prototype will cause two objects to share the same prototype. Therefore, changing the prototype of any object affects the prototype of another object. In most cases, this is not the expected result.

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.