Scoped Security Constructor _ function

Source: Internet
Author: User

Problem Introduction:

Before see "JS language Essence", introduce the dross of JS language, one of them is the global object . When you use a constructor, you may forget to write new, and the object is added to the Global object window, causing an unexpected increase in the Error object properties.

For example, a constructor:

function Person (gender,age) {
    this.gender = gender;
    This.age = age;
}

The correct way to open it should be var p = new Person (), which points to the newly created object. But when you forget to use new, such as var p1 = person (), the equivalent of calling the function directly, this points to the global object.

var p = new Person (' female ',);
Console.log (P.gender); Wei
console.log (window.gender);//undefined

var p1 = person (' male ', n);
Console.log (P1.gender); Error,p1 is undefined
console.log (window.gender);//xiao

scoped Security Constructor : Returns a new instance of person regardless of whether or not to use new.

function Polygon (sides) {if (this instanceof Polygon) {this.sides = sides;
      This.getarea = function () {return 0;
    } else {return new Polygon (name);
    } function Rectangle (width, height) {Polygon.call (this, 2);//Borrow constructor this.width = width;
    This.height = height;
    This.getarea = function () {return this.width * this.height; } Rectangle.prototype = new Polygon ();

  Prototype chain inheritance, which implements the rectangle instance is also a Polygon instance, thereby passing the checksum of ' if (this instanceof Polygon) ' in the Polygon constructor.
  var rect = new Rectangle (5,10); alert (rect.sides); 

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.