JavaScript creates an object's function construction pattern and the prototype pattern use together (four)

Source: Internet
Author: User
Tags define object constructor return

A common way to create custom types is to use the constructor pattern in combination with the prototype pattern.

The constructor pattern is used to define the specific parts (properties and methods) of the instance object, and the prototype pattern is used to define the shared part.

This saves the maximum memory overhead.

function Human (name, sex) {            this.name = name;
            this.sex = sex;             this.getwife=function () {//Marry wife                  if (this.sex = = "Male") {                     return "
I want to marry a Wife ";                }                               Else                      return "I don't have to marry a wife";              }        }         Human.prototype.say = function () {            alert (
THIS.name);        }         var man = new Human ("Lv bu", "male")
;
        var woman = new Human ("Diao cicada", "female");         alert (Man.getwife ());//I want to marry my wife          Alert (Woman.getwife ());//I don't have to marry my wife         alert (Man.getwife = = Woman.getwife);//false         alert (man.say==woman.say);//true

This combination pattern has the advantage of the function construction pattern and the prototype model. Solved their own shortcomings. This combination mode is the most widely used and most popular way to create a custom type.



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.