Re-recognize the objects created in JavaScript (i)

Source: Internet
Author: User
Tags function definition

First, the order

Object-oriented has a flag, that is, they all have the concept of a class, and through a class can create any number of objects with the same properties and methods. ECMA-262 defines an object as a collection of unordered properties whose properties can contain basic values, objects, or functions.

Use object to create the object, as shown in the following code:

        var New Object ();         = "Kitten";         = "Black";         function () {            Console.log (this. color);        }

Use the object literal to create the object, as shown in the following code:

var animal = {            "Kitten",            "Black",            function  () {                Console.log (this. color);            }        ;

In both of these ways, although I created the object, but did not meet the object's encapsulation characteristics, I can not reuse this short code, only paste copy to create a new object, this is not the result I want, predecessors from the object-oriented design pattern

The idea of refining some new methods. We must stand on the shoulders of giants to see farther.

Second, the factory model

This pattern abstracts the process of creating concrete objects. ECMAScript cannot create a class, so a function is used to encapsulate the details of creating an object with a specific interface. As shown in the following code:

        ///Provide a method for constructing an animal object        functioncreateanimal (name, color) {varobj =NewObject (); Obj.name=name; Obj.color=color; Obj.print=function() {Console.log (name+ "The color is:" +color); }            returnObj//return Object        }        //instantiate an object        varAnimal1 = Createanimal ("Kitten", "Black"); Animal1.print ();

This mode, although the code can be reused, but does not solve the problem of object recognition, if we can declare object,array such as the original constructor is good, so there is a derivation of the constructor function;

Third, the constructor function

Familiar with C #, Java and other languages of friends, we know that in general, we have no parameter constructor, the parameters of the constructor function. Like an array, it belongs to a parameterless constructor. First look at the following code

        function Animal (name, color) {            this. Name = name;              this. color = color;              This function () {                Console.log (this. color);            }        }         var New Animal ("Kitten", "Black");        Animal1.print ();

We use a parametric constructor, which, compared to the factory model, does not explicitly create objects, assigns properties and methods directly to the This object, and does not have a return statement. By the Instanceof method we can derive the constructor function

The instantiation of it can be identified as a specific type;

        instanceof Object);//true        instanceof Animal);//true

The main problem with constructors is that each method is recreated on each instance. The function in ECMAScript is an object, meaning that each function is defined, that is, an object is instantiated, so the print function in the above object is instantiated 2 times.

This is not necessary, so we can solve this problem by moving the function definition outside the constructor.

        function Animal (name, color) {            this. Name = name;              this. color = color;             this. Print = print        }        function  print () {            Console.log (  This  This . color);        }

But this new problem comes again, the function defined in the global scope can actually be called by an object, which makes the global scope a bit of a misnomer. So we have no encapsulation of this custom reference type. Then there's the prototype model to

Solve the problem.

Four, prototype mode

We create each function with a prototype (prototype) attribute, which is a pointer to an object, and the purpose of this object is to include properties and methods that can be shared by all instances of a particular type. As shown in the following code:

        function Animal () {        }        = "Kitten";         = "Black";         function () {            Console.log (this. color);        }         var New Animal ();        Animal.print ();

If we want to change the properties of this object, we can simply reassign its properties:

        var New Animal ();         = "Little tabby cat";        Animal.print ();

But in general, we like to assign values to objects when we create them, so I'm going to re-transform the code above with a parametric constructor.

        function Animal (name, color) {            this. Name = name;              this. color = color;        }         function () {            Console.log (this. color);        }         var New Animal ("Little Black Cat", "Black");        Animal.print ();

But to do so, if the parameters are too many will appear very long, sometimes when the argument is easy to error, according to my years of experience in C # code, for too long parameters, I generally like to put parameters into an object, as a parameter,

As shown in the following code:

        functionAnimal (setting) { This. Name =Setting.name;  This. color =Setting.color; } Animal.prototype.print=function() {Console.log ( ThisThe color of the. Name + "is:" + This. color); }        varsetting ={name:"Kitten", Color:Black        }; varAnimal =NewAnimal (setting); Animal.print ();

This encapsulation looks a lot more concise and personal love.

V. Conclusion

It was planned to go to bed early and get up early, and now it's 00:30, and it's too late to go to bed and wake up, restudying to this today, come on, old boy! Good night!

Re-recognize the objects created in JavaScript (i)

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.