Own objects: constructors and methods

Lecture




  1. Its object methods
  2. Access to the object through this
  3. Constructor function, "new"
  4. Creating methods in the constructor
  5. Private properties
  6. Total

Before that, we spoke of an object only as a store of values. Now let's go ahead and talk about the addition of objects of their own functions (methods), as well as constructors - functions that create objects.

Its object methods

When you declare an object, you can write a function. It becomes his method, for example:

01 var user = {
02    name: 'Василий' ,
03
04    // метод
05    sayHi: function () {
06      alert( 'Привет!' );
07    }
08
09 };
10
11 // Вызов метода
12 user.sayHi();

You can create a method later on by explicitly assigning:

01 var user = {
02    name: 'Василий'
03 };
04
05 user.sayHi = function () {
06    alert( 'Привет!' );
07 };
08
09 // Вызов метода:
10 user.sayHi();

Access to the object through this

To complete the work, the method must have access to the object data. In particular, the user.sayHi() call may want to display the username.

To access an object from a method, the this keyword is used . The value of this is an object in the context of which the method is called, for example:

1 var user = {
2    name: 'Василий' ,
3
4    sayHi: function () {
5      alert( this .name );
6    }
7 };
8
9 user.sayHi();

Here, when the user.sayHi() function is user.sayHi() , this will store a reference to the current user object.

In this case, instead of this you could use the variable: alert( user.name ) , but the user object can be transferred somewhere, the user variable is overwritten, and so on. Using this ensures that the function works exactly with the object in the context of which it is called.

Through this you can refer to any property of the object, and if you want to transfer it somewhere:

01 var user = {
02    name: 'Василий' ,
03
04    sayHi: function () {
05      showName( this ); // передать текущий объект в showName
06    }
07 };
08
09 function showName(obj) {
10    alert( obj.name );
11 }
12
13 user.sayHi();

Importance: 5

Create a calculator object with three methods:

  • readValues() requests two values ​​for the prompt and saves them as object properties
  • sum() returns the sum of two values.
  • mul() returns the product of two values

The tutorial / intro / object / calculator.html demo page shows the result of the code:

1 var calculator = {
2    ... ваш код...
3 }
4
5 calculator.readValues();
6 alert( calculator.sum() );
7 alert( calculator.mul() );

Decision

tutorial / intro / object / calculator.html

[Open task in new window]

Importance: 2

There is a ladder object ladder:

01 var ladder = {
02    step: 0,
03    up: function () { // вверх по лестнице
04      this .step++;
05    },
06    down: function () { // вниз по лестнице
07      this .step--;
08    },
09    showStep: function () { // вывести текущую ступеньку
10      alert( this .step);
11    }
12 };

Now it's boring to work with him:

1 ladder.up();
2 ladder.up();
3 ladder.down();
4 ladder.showStep(); // 1

Modify the code so that calls can be made as a chain, like this:

ladder.up().up().down().up().down().showStep(); // 1

This approach is used, for example, in the jQuery framework.

Decision

The solution is to return the current object each time. This is done by adding return this at the end of each method:

01 var ladder = {
02    step: 0,
03    up: function () {
04      this .step++;
05      return this ;
06    },
07    down: function () {
08      this .step--;
09      return this ;
10    },
11    showStep: function () {
12      alert( this .step);
13      return this ;
14    }
15 }
16
17 ladder.up().up().down().up().down().showStep(); // 1

[Open task in new window]

Constructor function, "new"

The usual {...} syntax allows you to create a single object. But often you need to create a lot of similar objects.

For this purpose, functions are used by launching them using the special operator new .

The constructor is any function called via new .

For example:

1 function Animal(name) {
2    this .name = name;
3    this .canWalk = true ;
4 }
5
6 var animal = new Animal( "ёжик" );

Any function can be called with new . However, it works in a slightly different way than usual:

  1. A new, empty object is automatically created.
  2. The special keyword this gets a link to this object.
  3. The function is executed. As a rule, it modifies this , adds methods, properties.
  4. Returns this .

So the result of executing the example above is an object:

1 animal = {
2    name: "ёжик" ,
3    canWalk: true
4 }

The object being created is said to be “an object of class (or type) Animal ”.

The term "class" here is professional jargon. In many other programming languages ​​there is a special entity “class”. It is not in JavaScript, but something similar can be organized, which is why it is called so.

The function may return another object instead of this

If the function explicitly returns an object, it will be returned, and not this .

For example:

1 function BigAnimal() {
2
3    this .name = 'Мышь' ;
4
5    return { name: 'Годзилла' }; // <-- будет возвращено
6 }
7
8 alert( new BigAnimal().name ); // Годзилла

If the function does not return an object, for example, a number, then such a call to return will not affect anything. For example:

1 function BigAnimal() {
2
3    this .name = 'Мышь' ;
4
5    return 'Годзилла' ; // не объект, такой return в режиме new ни на что не влияет
6 }
7
8 alert( new BigAnimal().name ); // Мышь

This feature of the work of new spelled out in the standard, it is useful to know about it, but it is used very rarely.

The names of functions that are intended to create objects, as a rule, begin with a capital letter.

By the way, when calling new with no arguments, brackets can be omitted:

var animal = new BigAnimal; // <-- без скобок
// то же самое что
var animal = new BigAnimal();

Importance: 2

Are such functions A and B possible in the example below, that the corresponding objects a,b are equal (see the code below)?

1 function A() { ... }
2 function B() { ... }
3
4 var a = new A;
5 var b = new B;
6
7 alert( a == b ); // true

If yes, give an example of a code with such functions.

Decision

Yes, it is possible.

They must return the same object. Moreover, if the function returns an object, this not used.

For example, they can return the same obj object defined outside:

1 var obj = {};
2
3 function A() { return obj; } obj; }
4 function B() { return obj; } obj; }
5
6 var a = new A;
7 var b = new B;
8
9 alert( a == b ); // true
created: 2014-10-07
updated: 2021-03-13
132480



Rating 9 of 10. count vote: 2
Are you satisfied?:



Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Scripting client side JavaScript, jqvery, BackBone

Terms: Scripting client side JavaScript, jqvery, BackBone