How to optimize the JavaScript constructor

Source: Internet
Author: User

First, we look at a constructor, user, when we call user to create an instance, we usually write the new operator.here, if you call the constructor using the New keyword, the this in the constructor always points to a completely new object (that is, the user's instance), and if you do not use new, this points to the global object。 The user constructor is defined as follows:
function User (name, PasswordHash) {    this. Name = name;      this. PasswordHash = PasswordHash;}

The correct invocation method for the user constructor should be as follows:
var u = new User ("Baravelli", "d8b74df393528d51cd19980ae0aa028e");
But what if the caller forgot to add the new keyword because of carelessness? Let's Test it together:
var u = User ("Baravelli", "d8b74df393528d51cd19980ae0aa028e"//  undefined   This//" Baravelli"this/ / "d8b74df393528d51cd19980ae0aa028e"
The result constructor actually returns undefined!! This is also very normal, because without the new keyword, call him directly, it is not any different from calling the normal function, and the user has no return statement, so the return value of course is undefined. What's worse, if you don't add the new call, the user's inside of this will point to the global object, then it will destroy the global object, imagine, if the global object itself exists the name and PasswordHash these two variables, then their values will be modified, The harm is very great.if, in the constructor user, the strict mode of ES5 is turned on, the error will be thrown without using the new operator because this binding fails (note: This is not allowed to point to global objects in strict mode)As follows:
function User (name, PasswordHash) {    "use strict";     this. Name = name;     this. PasswordHash =var u = User ("Baravelli", "d8b74df393528d51cd19980ae0aa028e"); // error:this is undefined

In this case, a type error will be thrown //error:this is undefined。 However, this constructor is still fragile because it works only when the new operator is added. If we implement a constructor, add the new keyword can work properly that is more robust! In fact, it is not too difficult to implement, we just have to judge in the user constructor whether this point to the user instance is OK, if not just create a user instance, as follows:
function User (name, PasswordHash) {    if (!) (  This instanceof User)) {        returnnew  User (name, PasswordHash);    }     this. Name = name;     this. PasswordHash = PasswordHash;}
Now, whether you use the New keyword to call the constructor, he can work and test:
var x = User ("Baravelli", "d8b74df393528d51cd19980ae0aa028e"); var New User ("Baravelli","d8b74df393528d51cd19980ae0aa028e"instanceof//  True  instanceof//  true
However, the implementation of the above method also has a disadvantage, because it calls the user constructor twice (when the new keyword is not used), so the performance is reduced! Also, one problem is that it can be difficult to implement for a variable parameter constructor.. A better approach is to use the Object.create method of ES5:
function User (name, PasswordHash) {    varThisinstanceof this : Object.create (User.prototype);     = name;     = PasswordHash;     return Self ;}

This method, with the help of the Object.create method, takes User.prototype as a parameter and creates a new object that inherits the user.However, this method is also flawed, as we have said earlier, Object.create is the new standard of ES5, in some old environments may not work。 So, we also have to judge whether Object.create exists. , if it does not exist, it is manually implemented:
if (typeof object.create = = = "undefined") {    function(prototype        ) {  function  C () {}        = prototype;         return New C ();    };}

Finally, it should be reminded that if your constructor must use the New keyword, then you must write the document description, so as not to be called when others do not use the new operator, produce unexpected results!

How to optimize the JavaScript constructor

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.