<<javascript patterns>> Reading Notes – 3rd chapter literals and Constructors

Source: Internet
Author: User

Object literal

First, the definition syntax for the object literal is given:

1. Define the object in pairs of parentheses (opening curly brace "{" and closing brace "}")

2. The properties and methods are separated by commas in the object. Each property or method appears in the form of Key-value, separated by a colon between key and value.

3. When assigning a value to a variable, do not forget the semicolon after the curly brace

Empty Object

var obj = {};

This defines an empty object, but it is not nothing, at least it has properties and methods inherited from Object.prototype.

The object from the constructor

Grammar:

// anti-pattern, not recommended for this purpose New  = ' Zhang San ';

Literal objects have fewer characters to enter than the way literal objects are created,

Also, when a local function is created, the interpreter needs to query the scope chain from the object () position until the global object constructor is discovered.

When you create an object using the object () constructor, you cannot determine its type until the code runs, borrowing examples from the book:

//Create an empty objectvarO1 =NewObject (); Console.info (O1.constructor= = Object);//true//Create a numeric objectvarO2 =NewObject (7); Console.info (O2.constructor= = number);//true//Create a String objectvarO3 =NewObject (' Hello World '); Console.info (O3.constructor= = String);//true

In all, do not use new object to create objects, you should use the method of object literals.

Custom constructors and their return values

// define a person constructor function Person (name) {    this. Name = name;       This function () {        console.info (' hello! ' );    };};

When you call the constructor with new, a This object is created inside the function and the properties and methods are added to the this object.

The This object is then implicitly returned (if there is no explicit return statement).

Of course the constructor can explicitly return an object, for example:

function Person () {    this. Name = ' Zhang San ';      // creates a that object and returns the object    var that = {};     = ' John Doe ';     return that ;} var New  //  John Doe

As seen above, the constructor can return any object, as long as it is an object.

If the constructor attempts to return a non-object, which does not cause an error, but ignores this return value, continue to return this, for example:

function Person () {    this. Name = ' Zhang San ';      this. Age =;     return // an attempt was made to return a non-object, ignored, to return this }varnew//  Zhang San

Forcing the use of new mode

The constructor is also a function, except that it is called with the new operator.

If you forget to use the new operator when calling, the this in the constructor will point to the global object,

In a browser environment this will point to the Window object, where all of the properties or methods can be accessed only through the Window object, or directly, which is obviously not what you want to see.

//constructor FunctionfunctionPerson () { This. msg = ' Hello ';}//defining an ObjectvarP1 =NewPerson (); Console.info (typeofp1);//ObjectConsole.info (P1.MSG);//Hello//anti-pattern: forgot to use newvarP2 =Person (); Console.info (typeofP2);//undefinedConsole.info (msg);//HelloConsole.info (WINDOW.MSG);//Hello

The above problems have been solved in the ECMAScript5, but in the non-EC5 environment, we need to find a way to solve the above problems.

Naming conventions

The function that begins with the upper-case letter is a constructor, which must be called with new, the first letter of the normal function is lowercase and can be called directly.

Use that

The Convention is just a promise, the following pattern ensures that a property or method is not added to the global object even if you do not use new.

//defining Constructors-1functionPerson1 () {varthat = {}; That.name= ' Zhang San '; returnthat ;}//defining Constructors-2functionPerson2 () {return{name:' John Doe '    };}//in both of these ways, an object is always returnedvarP1 =NewPerson1 (), P2=Person1 (); Console.info (p1.name);//Zhang SanConsole.info (P2.name);//John Doe

However, the above two modes lose links to their own prototypes, which are not available to objects when they are expanded, for example:

//defining Constructors-1functionPerson1 () {varthat = {}; That.name= ' Zhang San '; returnthat ;}//extending the Person1 prototypeif(typeofPerson1.prototype.say = = = ' undefined ') {Person1.prototype.say=function() {Console.info (' Hello world ... '); }}varP1 =NewPerson1 ();p 1.say ();//TypeError:p1.say is not a function

Self-invoking constructors

In order to solve the problem of the above two modes, you can refer to the following solution,

Just inside the constructor, check that the This object is an instance of the constructor, and if not, use the new operator to call the constructor again to create the object, with the following code:

//Defining ConstructorsfunctionPerson () {//Note this instanceof person needs to be enclosed in parentheses.    if(! ( This instanceofPerson )) {        return NewPerson (); }     This. Name = ' Zhang San ';}//extend its prototypesif(typeofPerson.prototype.say = = = ' undefined ') {Person.prototype.say=function() {Console.info (' Hello world ... '); }}varP1 =NewPerson (), P2=Person (); Console.info (p1.name);//Zhang SanP1.say ();//Hello world ...Console.info (P2.name);//Zhang SanP2.say ();//Hello world ...

Array literal

It is recommended to use literal methods to create an array, mainly because the array literal is simple and unambiguous, and the second is because of the particularity of the array constructor.

When a single numeric value is passed to the array () constructor, it does not become the first element of the array, but instead sets the length of the array.

However, there are no actual elements in the array, so the undefined is returned when the elements of the array are accessed. Here are a few small examples:

varARR1 = [7];console.info (arr1.length); //1Console.info (Arr1[0]);//7varARR2 =NewArray (7); Console.info (arr2.length); //7Console.info (Arr2[0]);//undefinedvarARR3 = [3.14];console.info (arr3.length); //1Console.info (Arr3[0]);//3.14varARR4 =NewArray (3.14);//rangeerror:invalid Array LengthConsole.info (arr4.length); Console.info (arr4[0]);

Check the properties of an array

Use typeof to operate on an array, and return a value of "object" because it is also an object, but with little meaning.

You can determine whether an array is not by checking the length property or the slice () method, but other custom objects can also have these properties and methods.

The Array.isarray () method is defined in ECMASCRIPT5 to determine that the object is not an array, but the method cannot be used in an environment that does not support EC5. However, you can still detect whether an array is in the following ways:

if (typeof Array.isarray = = = ' undefined ') {    function(arg        ) {return Object.prototype.toString.call (arg) = = = ' [Object Array] ';    }}

<<javascript patterns>> Reading Notes – 3rd chapter literals and Constructors

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.