Calling a function in JavaScript in the form of a constructor

Source: Internet
Author: User
Tags assert

Transferred from: http://www.cnblogs.com/Saints/p/6012188.html

The constructor function (Constructor functions) is defined in the same way as any other function, and we can use function declarations, function expressions, or function constructors (see previous essays) to construct function objects. The difference between a function constructor and other functions differs from how they are called.

To invoke a function as a constructor, simply add the new keyword to the function name at the time of the call, for example: function Whatsmycontext () {return this;}; Call: New Whatsmycontext ();

Calling a function as a constructor is a very powerful feature in JavaScript, and here's a look at its mysteries:

12345678910111213 functionNinja() {  this.skulk = function() {    returnthis;  };}varninja1 = newNinja();var ninja2 = newNinja();assert(ninja1.skulk() === ninja1,  "The 1st ninja is skulking");assert(ninja2.skulk() === ninja2,  "The 2nd ninja is skulking");

The above demo first defines a constructor function that creates a function property named Shulk on the function's context object. It then creates two ninja (type) objects by invoking the function Ninja as constructors, and is referenced by NINJA1 and NINJA2 respectively, and finally validates the Skulk method of each object with a custom function assert. Each Shulk method should return a function object that is constructed every time the ninja is called in new mode.

Let's take a look at what's going on in this process:

1. A completely new empty object is created;

2. This empty object is passed to the constructor function and as its this parameter, so it becomes the context object of this constructor function;

3. Add a property on this new empty object, Shulk

4. The constructed object is returned as the return value of the function.

The purpose of using a constructor function is to create a new object, manipulate the object, and return the object as the return value of the constructor function. Any function unrelated to this purpose is not suitable as a constructor function. Call this function as a constructor when the function has no return value returns the newly created context object, so what happens when the function returns a value (base type)? Look at the following example:

12345678910111213 functionNinja() {  this.skulk = function() {    returntrue;  };    return1}assert(Ninja() === 1,"Return value honored when not called as a constructor");varninja = newNinja();assert(typeofninja === "object","Object returned when called as a constructor");assert(typeofninja.skulk === "function","ninja object has a skulk method");

Running the above example, all assertions are available, in fact the Ninja function returns a simple type whose value 1 does not have any effect on the execution of the code: if you call Ninja as a function, it returns 1, and it is called as a constructor, which returns the function context object created by new. What happens if the function returns another object?

1234567891011121314 varpuppet = {  rules: false};functionEmperor() {  this.rules = true;  returnpuppet;}var emperor = newEmperor();assert(emperor === puppet,  "The emperor is merely a puppet!");assert(emperor.rules === false,  "The puppet does not know how to rule!");

This time, unlike the example above, first create a puppet object and set its rules property to false, then define a function named Emperor, and set the Rules property of its context variable to true. But the function finally returns the global puppet object as the return value. And then call the Emperor function in the form of a constructor, which produces an ambiguous case, we get an object as a function context (this), but we return an entirely different object, in which case which object is returned?

As you can see from the assertion test of the following Assert function, the puppet function is returned. Here's a summary:

1. If the constructor function returns an object, the object is returned as the return value of the new expression, and the object that is generated as a function context (this) is discarded when the function is called in new mode;

2. If the constructor function does not return an object (the return value is a value type), the returned value is discarded, and the object that is generated as a function context (this) is returned when the function is called in new mode.

Code habits for constructor functions:

The purpose of the constructor function is to initialize and return the context object that is generated when the function is called, although these constructor functions can be called in the form of a function or a method, which generally does not make sense, such as:

function Ninja () {    this.skulk = function () {      return this;    };} var whatever = Ninja ();

Simply calling Ninja,skulk as a function is bound to the global variable window (not strict mode), which is not particularly useful and is more meaningless in strict mode because the context object this is undefined, Therefore throws an exception that cannot be set for the undefined property. In non-strict mode, this is prone to inexplicable situations, which is difficult to detect because it does not throw any exceptions.

Because constructor functions are also normal functions, they are called only in different ways, and typically there are different naming conventions for the definition of constructor functions:

Start with a verb to describe what it is to do and the first letter lowercase function name is suitable for normal function or object method; The constructor function is usually named as a noun that describes the object to be created and the first letter is usually capitalized.

Calling a function in JavaScript in the form of a constructor

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.