Designers of objects. Creating objects in javascript What is a designer in js

Function User (Name, Age) (this.name \u003d name; this.age \u003d age; this.sayhi \u003d function () (Console.log ("Hello!");)) Let user \u003d new user ("Homer", 33); Console.log (user.name);

Each object created using the constructor is an implicitly added Constructor property containing a reference to the constructor with which the object was created:

Console.log (user.constructor \u003d\u003d\u003d User); // True.

The Constructor property is intended to identify the object type. The same allows an InstanceOF operator:

Console.log (User InstanceOF User); // True.

When using a designer to create an object, a copy of properties and methods created for each object created.

Template "Prototype"

When a feature is created, the Prototype property is added to it. The Prototype property value is an object containing common properties and methods that are available to all objects created using this designer.

Instead of specifying properties and methods in the designer, they can be specified directly to the prototype:

Function user () () user.prototype.name \u003d "HOMER"; User.prototype.age \u003d "33"; User.prototype.sayhi \u003d function () (Console.log ("Hello!");); Let user \u003d new user (); Console.log (user.name);

By default, all prototypes have only the Constructor property containing a reference to the function to which it belongs:

FUNCTION FOO () () CONSOLE.LOG (Foo.Prototype.constructor \u003d\u003d\u003d foo); // True.

All other methods and properties are inherited from the Object type. When a new object is created using the designer, the internal pointer is defined in it to the designer prototype. Access to this pointer can be obtained using the Object.getProtypeOF () method:

FUNCTION FOO () () LET OBJ \u003d NEW FOO (); Console.log (Object.getPrototypeof (OBJ) \u003d\u003d\u003d Foo.Prototype); // True.

When reading the properties of the object begins its search. First, the property S. specified name Located in the object itself. If it is detected from the object, the property value is returned if the properties with the object with the object are not available, the search continues in the prototype. In the case of detection of property, the prototype returns its value. So the prototypes ensure the sharing of properties and methods in objects.

If an object is an add property with a name, like the properties of the prototype, then the object will create your own property, in this case, the following property will be used, and not the prototype property will be used.

To write less code, you can overwrite the prototype with a literal object containing all properties and methods:

Function User () () user.prototype \u003d (Name: "Homer", Age: 33, Sayhi: Function () (Console.log ("Hello!");)); // Restore the properties of the Constructor Object.DefineProperty (User.Prototype, "Constructor", (Enumerable: False, Value: User));

In this example, the user.prototype property is assigned a new object created by literal. It completely replaces the object offered by default. The result is the same as in the previous example, in one exception: the Construction property no longer indicates the user function. Explicit addition of the Constructor property with the user value in the object literal solves this problem. The Constructor property in the built-in default objects is incomprehensible, so the Object.DefineProperty () method was used to add it.

Combining Templates "Designer" and "Prototype"

Using the designer, its own properties determine, and using the prototype - general methods and properties:

Function User (Name, Age) (this.name \u003d name; this.age \u003d age;) user.prototype.sayhi \u003d function () (Console.log ("Hello!");)

JavaScript flexibility allows you to create objects with a variety of ways. But as it often happens, a variety of lifting a lot of pitfalls in itself. From this article, you will learn about how to see and get into these dangerous reefs.

Basics of the basics

We will not be reminded that objects in JavaScript represent themselves and how they can be created. An object in JavaScript is just a hash table of keys and values. If values \u200b\u200bare basic types or other objects, they are called propertiesif these are functions, they are called methods object.

The objects created by the user can be changed at any point of execution of the script. Many properties of embedded objects are also variable. That is, you can simply create an empty object and add properties and methods to it as needed. The easiest way to do this with literal notation:
// Create an empty object Var Cat \u003d (); // Add property: cat.name \u003d "Garfield"; // or method: cat.getname \u003d function () (RETURN CAT.NAME;);
Another way to create an object is to use designers functions:
// Literal notation: var cat \u003d (Name: "Garfield"); // Designer function: var cat \u003d new object (); Cat.name \u003d "Garfield";
Obviously, the literal notation is shorter than the designer. There is also a philosophical reason to prefer the literal notation of the designers: it emphasizes that the object is just a variable hash, and not something created by the template specified class.

In addition, the use of the Object constructor forces the interpreter to check whether this function is redefined in the local context.

Object Design Underwater Stone

There is no reason to use the Object constructor. But we all know that sometimes you have to use some kind of old code, and in this case it is useful to know about one character of this designer. It takes an argument, and depending on its type, it can entrust the creation of an object to another built-in constructor; As a result, we will not get the object that we expected:
// Empty object var O \u003d new Object (); O.CONSTRUCTOR \u003d\u003d\u003d OBJECT; // True Var O \u003d New Object (1); O.CONSTRUCTOR \u003d\u003d\u003d NUMBER; // True Var O \u003d New Object ("String"); O.CONSTRUCTOR \u003d\u003d\u003d STRING; // True // We did not assume that the created object will have this method: Typeof O.Substring; // "FUNCTION"
Such behavior of the Object designer can lead to unexpected results if we transmit a value that is unknown at the execution phase.

Moral is obvious: do not use the Object constructor.

Own designers

We can define our own constructors. Use them looks like this:
Var Cat \u003d New Cat ("Garfield"); cat.say (); // "I am Garfield"
The syntax is similar to the Java constructor, but in JavaScript, the designer is a conventional function and is therefore defined as follows:
var cat \u003d function (name) (this.name \u003d name; this.say \u003d function () (Return "I am" + this.name;))
When calling this designer with the NEW operator inside the function, the following happens:
  • a blank object is created, which is specified by this variable; This object inherits the function prototype;
  • properties and methods are added to the object stored in this;
  • the object stored in this is implicitly returned at the end of the function (because we did not return anything).
For simplicity in the example, the Say () method is added to the object. It is not very good, as every time you call New Person () will be created in memory new feature. Since the Say () method is the same for all objects created using this designer, it is better to add it to the prototype CAT:
Cat.prototype.say \u003d function () (Return "I am" + this.name;);
In addition, it is not entirely correct to argue that the object of this implicitly created in the designer is empty: it is inherited from the prototype CAT, but the consideration of prototypes is beyond the scope of this article.

What returns the designer

When using the new operator, the constructor always returns the object. By default, this is an object referenced by this. The designer returns this implicitly, however, we can explicitly return any other object, for example:
var cat \u003d function () () (this.name \u003d "I am Garfield"; var true \u003d (); that.name \u003d "i am cat-woman"; RETURN THAT;); Var Cat \u003d New Cat (); Cat.name // "I am Cat-Woman"
Thus, we can return any value from the designer, but only if it is an object. If we try to return, say, a string or false, it will not be mistaken, but the return operator will be ignored, and the designer will return this.

Covarian New.

Designers are just the functions called with the new operator. What happens if you forget this operator? The interpreter will not give warnings, but this will lead to logical errors. The this variable will not specify the object inherited from the prototype of the designer, and on the global object (Window in the case of a browser):
Function Cat () (this.name \u003d "Garfield";) // New object var cat \u003d new cat (); Typeof Cat; // "Object" cat.name; // "Garfield" // Forget New: Var Cat \u003d Cat (); Typeof Cat; // "undefined" window.name; // "Garfield"
In strict mode, ECMAScript 5 This event in this case will not indicate the global object. Let's see how this error can be avoided if ECMAScript 5 is not available.
Functional Naming Agreements
Most. simple way It is strict compliance with the information naming agreements: we begin the usual functions from the lowercase letter (MyFunction ()), and the functions-designers with the title (MyConstruction ()). Unfortunately, such a way does not save anything.
Explicit refund
Designers can return any objects. Programmers can take advantage of this:
FUNCTION CAT () (VAR THAT \u003d (); that.name \u003d "Garfield"; Return That;)
The name of the variable is chosen arbitrarily, this is not part of the specification. With the same success, we can call the Returned object Me or Self or as you please.

For simple objects, such as created in the example, we can do without additional variables at all, using the literal notation:
FUNCTION CAT () (RETURN (Name: "Garfield");)
Such a designer will always return the object, regardless of how to call it:
var first \u003d new cat (), second \u003d cat (); first.name; // "Garfield" Second.name; // "Garfield"
This method has a serious disadvantage: the object does not inherit the prototype of the constructor, that is, the methods and properties added directly to the CAT will not be available to the objects created with it.

Constructor self-saying
To solve this problem, it is enough to check whether this is in the constructor's body by an ectery of this very designer, and if not, cause yourself again, but this time with the new operator. It sounds scary, but in fact just:
FUNCTION CAT () (IF (! (This InstanceOf Cat)) (Return New Cat ();) This.name \u003d "Garfield";) cat.prototype.meow \u003d "MEOW!"; var first \u003d new cat (), second \u003d cat (); first.name; // "Garfield" Second.name; // "Garfield" first.Meow; // "MEOW!" Second.Meow; // "MEOW!"
If our designer is subsequently renamed, it will have to rule his body. You can avoid this by checking arguments.callee instead of the design name:
If (! (this instanceof arguments.callee)) (Return new arguments.callee ();)
Here we took advantage of the fact that an arguments object is created within each function containing all the parameters transmitted to the functions at the time of the call. The Callee property of this object indicates the called function. But here you need to take care: the strict mode ECMAScript 5 causes the exception of Typeerror when contacting this property, so it is worth a choice between the convenience of refactoring and light tomorrow.

Instead of imprisonment

JavaScript is a stunning language. It is easy enough to master, and the existing frameworks will make it easily use it in their projects. But behind the simplicity of the syntax is hidden whole reefs of underwater stones - and very powerful tools. Sometimes it is useful to watch, what's there at the bottom.

JavaScript provides developers with the opportunity to create objects and work with them. For this, there are the following techniques:

  • Operator NEW.
  • Literal notation
  • Designers of objects
  • Associative arrays

Use the new statement

It is probably the most easy way Creating an object. You simply create the name of the object and equate it to the new javaScript object.

// Create our VAR MYOBJECT \u003d NEW OBJECT () object; // variables myobject.id \u003d 5; // The number myobject.name \u003d "sample"; // Row // Functions MyObject.getName \u003d Function () (Return this.name;)

Minus this method It is that you can only work with one newly created object.

// Use our Alert object (MyObject.GetName ());

Literal notation

The literal notation is a somewhat unusual way to identify new objects, but easy to understand. The literal notation works with JavaScript 1.3.

// Create our object using MyObject \u003d (ID: 1, Name: "sample", BOOLVAL: TRUE, GetName: FUNCTION () (RETURN THIS.NAME;))

As you can see, it is quite simple.

Object \u003d (identifier: value, ...)

And an example of using:

Alert (myobject.getname ());

Designers of objects

Object designers are a powerful tool for creating objects that can be used repeatedly. The designer of the object is, in fact, the usual javaScript featurewhich can also be transmitted different parameters.

Function MyObject (ID, NAME) ()

Just we wrote the constructor. With it, we will create our object.

Var myfirstobjectInstance \u003d New MyObject (5, "sample"); var mysecondobjectInstace \u003d New MyObject (12, "OTHE Sample");

Thus, we created various instances of the object. Now we can work separately with each instance of the MYOBJECT object, without fearing the fact that changing the properties of one instance, we will affect the properties of another instance.

As in the OOP, myObject can have methods and various properties. The properties can assign default values \u200b\u200bor the values \u200b\u200btransferred by the user in the object constructor.

Function MyObject (ID, NAME) (// Values \u200b\u200btransmitted by this._ID \u003d id; this._name \u003d name; // default value this.defaultValue \u003d "(! Lang: MyDefaultValue"; } !}

Similarly, we can create both functions.

Function MyObject (ID, NAME) (this._id \u003d id; this._name \u003d name; this.DefaultValue \u003d "(! Lang: MyDefaultValue"; //Получение текущего значения this.getDefaultValue = function() { return this.defaultvalue; } //Установка нового значения this.setDefaultValue = function(newvalue) { this.defaultvalue = newvalue; } //Произвольная функция this.sum = function(a, b) { return (a+b); } } !}

Associative arrays

Such a method will be useful to streamline a large number of same type objects.

Var MyObject \u003d New Number (); MYOBJECT ["ID"] \u003d 5; MyObject ["Name"] \u003d "samplename";

To bypass such objects, you can use such a cycle:

For (MyElement in MyObject) (// bypass code // in myElement - recording identifier // in MyObject - content recording)

The material prepared a small scheme.

You can see it in the formats.

FUNCTION PERSON (FIST, LAST, AGE, EYE) (this.firstname \u003d first; this.lastname \u003d last; this.age \u003d age; this.eecolor \u003d Eye;)

It is considered a good programming practice so that the name of the functions of the designers began with a capital letter.

Object Types (Templates) (Classes)

Examples from previous heads are significantly limited. They create only single objects.

However, sometimes it is required to have a certain "template", which could be created by many objects of the same "type".

To create a "object type" and used function Designer Object.

In the example of this chapter, the example function Person () It is the function of the object designer.

Objects of the same type are created using a constructor function call with a keyword new:

Var MyFather \u003d New Person ("John", "DOE", 50, "Blue"); Var Mymother \u003d New Person ("Sally", "Rally", 48, "Green");

Keyword THIS

In javascript. keyword tHIS Indicates an object that "belongs" to this code.

Keyword value tHISWhen it is used in the object, the object itself is.

In the designer function from the keyword tHIS No value. This is a "substitution" for a new object. When a new object is created, then the key word value tHIS And this new object will be.

note that tHIS This is not a variable, but a keyword. You can not change its value.

Adding Properties to Object

Add a new property to an existing object is very simple:

MyFather.Nationality \u003d "English";

The property will be added to the MyFather object, but not to the MYMOTHER object. (Or any other Person type object).

Adding a method to the object

Add new method To the existing object is very simple:

MyFather.name \u003d function () (Return this.firstName + "" + this.lastname;);

The method will be added to the MyFather object, but not to the MYMOTHER object. (Or any other Person type object).

Adding a property to an object constructor

You cannot add a new property to the object constructor in the same way as it is done in the case of an existing object.

To add a new property to the constructor, you must add it to the designer function:

FUNCTION PERSON (FIST, LAST, AGE, EYECOLOR) (this.firstName \u003d first; this.LastName \u003d Last; this.age \u003d age; this.eyecolor \u003d eyecolor; this.Nationality \u003d "English";)

In this case, the default properties can be set.

Adding a method to object constructor

The designer function can also determine the methods:

FUNCTION PERSON (FIST, LAST, AGE, EYECOLOR) (this.firstname \u003d first; this.lastname \u003d last; this.age \u003d age; this.eecolor \u003d EyeColor; this.name \u003d function () (Return this.firstName + " "+ this.lastname;);)

You can not add new methods to the object constructor in the same way as it is done in the case with an existing object. Adding methods to an object must occur inside the designer function:

Function Person (FirstName, Lastname, Age, EyeColor) (this.firstName \u003d FirstName; this.lastname \u003d LastName; this.age \u003d age; this.eyecolor \u003d EyeColor; this.ChangeName \u003d Function (Name) (this.lastname \u003d name ;);)

The ChangeName () feature assigns the Name parameter value to the LastName property of the Person object:

Mymother.ChangeName ("DOE");

JavaScript knows what object is speaking, "substituting" in the keyword tHIS an object mymother..

Built-in JavaScript Designers

JavaScript has built-in designers for their own objects:

Var x1 \u003d new object (); // New object Object VAR X2 \u003d New String (); // New object String VAR X3 \u003d new number (); // New object Number VAR X4 \u003d New Boolean (); // New object BOOLEAN VAR X5 \u003d NEW Array (); // New ARRAY VAR X6 \u003d New Regexp (); // New object Regexp VAR X7 \u003d New function (); // New object FUNCTION VAR X8 \u003d New DATE (); // New Date Object

There is no Math () object in this list, since this is a global object. NEW keyword cannot be used with Math object.

Did you know?

As can be seen from the above code, JavaScript has object versions of primitive data types String, Number and Boolean. However, there is no reason to create comprehensive objects for these types. Primitive values \u200b\u200bwork faster.

In this way:

  • use object literals { } Instead of New Object ().
  • use string literals "" Instead of new string ().
  • use numeric literals 12345 Instead of NEW Number ().
  • use logical literals true / False Instead of new boolean ().
  • use literal arrays instead of New Array ().
  • use literal templates /()/ Instead of new RexExp ().
  • use expressions of functions () {} Instead of New Function ().
var x1 \u003d (); // New object Object var x2 \u003d ""; // New primitive string Var x3 \u003d 0; // New primitive number var x4 \u003d false; // New primitive logical value var x5 \u003d; // New object Array var x6 \u003d / () /// New object Regexp var x7 \u003d function () (); // New object FUNCTION

content moved from Snippets to Articles

Using the NEW operator, you can create an object (Function object).
The NEW operator must specify the name of the designer; This function-designer initializes the properties of the object.
The designer function is transmitted to the conference keyword, which refers to the newly created object.

There are built-in JavaScript constructors, for example: array (), date (), regexp (). It is worth noting: the Object () constructor creates an empty object, which is equivalent to using the object literal ().

Prototype - This is the value of the Prototype property of the designer. Each function has the Prototype property, this property refers to a predefined prototype object. This object only works if the function is used as a constructor, that is, together with the NEW operator.

Each object has a property of Constructor; This property refers to the designer function, which, as mentioned above, initializes the properties of the object.

As you can see, the R_METHOD property always refers to an immutable (unlike properties that are unique to each object) function. Therefore, rationally add it to the prototype. We can make a simple conclusion: the prototype object is suitable for constants and methods. Since any object inherits the properties of its prototype, then our function (R_METHOD) is automatically added to all objects initialized by the designer (example_constr).

JavaScript classes

JavaScript does not support classes as such. However, you can create pseudo-schools using constructors and object prototypes. The designer is a class.

Construct assignment - Create a new object, install and return it as the value of the constructor.

The design name is usually nouns, written from a capital letter and describes the designed object. Designers, as a rule, are used to create objects corresponding to one template.

An example of creating an object
Designer definition,
and setting properties for the prototype:

// VAR OPA \u003d () object; var Opa_ \u003d (x: 0, y: "yes") var d \u003d new date (); // Current Date / * property Constructor * / Document.Write (D.Constructor); // Function date () () d.constructor \u003d\u003d date // true // Determine the designer: function example_constr (r, t) (this.ad \u003d r; this.ak \u003d t; // Method, but it is better to determine how SV-in prototype / * this.r_method \u003d function () (this.qu \u003d this.ad - this.ak;) * / // Method, but inside the method do not use the properties of the object.a_method \u003d function (x, y) (Alert (x + y);)) // declare the method (R_METHOD) in the prototype // is preferable than using R_Method in f-and constructor // Due to the fact that the R_Method's F-i does not have unique SV-B, in contrast // from the above properties (AD, AK) example_constr.prototype.r_method \u003d function () (this.qu \u003d this.ad - this. AK;) // Call the designer and create an example_constr (KROT) object var KROT \u003d new example_constr (14,15); // What is equivalent to Krot \u003d (AD: 14, AK: 15) krot.r_method (); // Will out: //alert.krot.qu); // -1 //krot.a_Method(11,11); // Will out: // 22

Addition:
To create your own designer, it is enough to describe the function in which this keyword will refer to objects (which are created by the designer function). See above using Example_Constr.

console.dir.

jS.

Console.dir (OBJ); // withdraw all properties of an object in the console

Objects in JavaScript allow you to recreate the concept of object-oriented programming.

In order to create objects one type Use functions-designers. The difference between the constructor from the usual function is that the constructor is called through a special NEW operator.

When using NEW, only an object can be returned in the RETURN constructor function, and this object will replace the default object that is returned by default.

Private variables and functions

The designed function can be like private data (Such data on the external code can be obtained, but cannot change) and public.

javascript.

// Determine the designer: FUNCTION EXAMPLE_CONSTR (R, T, NAME) (// this \u003d () is created automatically this.ad \u003d r; this.Ak \u003d T; this.a_method \u003d function (x, y) (Alert (x + y);) // Constructor function and without any Return // Returns the object that // Private variable (that is, it can be obtained from the external code, // but cannot be changed): this.getname \u003d function () (Return Name; ) // You can also use conventional variables, // which will be available in only the designer function limits: var PAGE, Password; var Ogo \u003d function () (// ............... .);) var newobj \u003d new example_constr (1,2, "Vasya"); Console.dir (NewObj); Console.log (newobj.getname ()); //

know

  • JavaScript objects work only with string properties, that is, if the property is not specified as a string, it will still become a string.