Valid JavaScript Item 33 makes the constructor no longer dependent on the new Keyword

Source: Internet
Author: User

Valid JavaScript Item 33 makes the constructor no longer dependent on the new Keyword

This series serves as the Reading Notes for javastivejavascript.

When using a function as a constructor, make sure that the function is called using the new keyword.


function User(name, passwordHash) {this.name = name;this.passwordHash = passwordHash;}

If you forget to use the new keyword when calling the above constructor, then:


var u = User("baravelli", "d8b74df393528d51cd19980ae0aa028e");u; // undefinedthis.name; // "baravelli"this.passwordHash; // "d8b74df393528d51cd19980ae0aa028e"

We can find that u is undefined, and this. name and this. passwordHash are assigned a value. However, this points to a global object.

If you declare the constructor to be dependent on the strict mode:


function User(name, passwordHash) {"use strict";this.name = name;this.passwordHash = passwordHash;}var u = User("baravelli", "d8b74df393528d51cd19980ae0aa028e");// error: this is undefined

If you forget to use the new keyword, A TypeError is thrown when you call this. name = name. This is because in strict mode, the default direction of this will be set to undefined rather than global objects.

Is there a way to ensure that a function can be used as a constructor no matter whether the new keyword is used or not when a function is called? The following code is an implementation method that uses the instanceof operation:


function User(name, passwordHash) {if (!(this instanceof User)) {return new User(name, passwordHash);}this.name = name;this.passwordHash = passwordHash;}var x = User("baravelli", "d8b74df393528d51cd19980ae0aa028e");var y = new User("baravelli", "d8b74df393528d51cd19980ae0aa028e");x instanceof User; // truey instanceof User; // true

The above if code block is used to handle the situation where new is not used for calling. When new is not used, this is not a User instance. When the new keyword is used, this is a User-type instance.

Another method that is more suitable for ES5 is as follows:


function User(name, passwordHash) {var self = this instanceof User ? this : Object.create(User.prototype);self.name = name;self.passwordHash = passwordHash;return self;}

The Object. create method is provided by es5. it can accept an Object as the prototype of the newly created Object. In a non-ES5 environment, you must first implement an Object. create method:


if (typeof Object.create === "undefined") {Object.create = function(prototype) {function C() { }C.prototype = prototype;return new C();};}

In fact, the Object. create method also has a version that accepts the second parameter. The second parameter represents a series of attributes assigned to the newly created Object.

When the preceding function is called with new, the new object is returned correctly. This benefits from Constructor Override Pattern ). This mode means that the return value of an expression with the new Keyword can be overwritten by an explicit return. As the above Code uses returnself to explicitly define the return value.

Of course, the above work is not necessary in some situations. However, when a function needs to be called as a constructor, it must be described. Document is a method, it is also a way to name a function using uppercase letters (based on some conventions in the JavaScript language ).

Summary:

  1. Use Object. create to ensure that a function is indeed called as a constructor, regardless of whether the new keyword is used.
  2. For a function as a constructor, specify this in the document to ensure that other users can use it correctly.

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.