7
7
75db772019-07-01 19:58:42
JavaScript
75db77, 2019-07-01 19:58:42

Do I understand the function (purpose) of the this word in this example correctly?

There is this code:

module.exports = function Cart(oldCart) {
    this.items = oldCart.items || {};                
    this.totalQty = oldCart.totalQty || 0;           
    this.totalPrice = oldCart.totalPrice || 0;

    this.add = function(item, id) {
        var storedItem = this.items[id];
        if (!storedItem) {
            storedItem = this.items[id] = {item: item, qty: 0, price: 0};
        }
        storedItem.qty++;
        storedItem.price = storedItem.item.price * storedItem.qty;
        this.totalQty++;
        this.totalPrice += storedItem.item.price;
    };

 this.reduceByOne = function(id) {              
        this.items[id].qty--;
        this.items[id].price -= this.items[id].item.price;
        this.totalQty--;
        this.totalPrice -= this.items[id].item.price;

        if (this.items[id].qty <= 0) {
            delete this.items[id];
        }
    };

As far as I understand, the this keyword is used to refer to the newly created object.
That is, if you take only these lines:
this.items = oldCart.items || {};
this.totalQty = oldCart.totalQty || 0;
this.totalPrice = oldCart.totalPrice || 0;
the newly created object looks like this:
var Cart = {
    items = oldCart.items || {},               
    totalQty = oldCart.totalQty || 0,           
    totalPrice = oldCart.totalPrice || 0
}

Or is there another function (purpose) of the word this? And it does not serve to refer to the newly created object?
But then this code goes: and another onda function: What is the function (purpose) of this this? Here I do not understand what this is for.
this.add = function(item, id)
this.reduceByOne = function(id)

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey P, 2019-07-01
@75db77

Hi.
in short, and about JS, then you are on the right track.
the keyword `this` indicates the execution context of the function, so the context can be changed accordingly.
explicit context change methods include the following methods: `bind`, `call`, `apply`, implicit methods include the "dot" operator (`obj.getName()`), the keyword `new` and other cases.
those 2 snippets that you indicated with `Сart` examples are not equivalent, although they do, approximately, the same thing.
Let's look at an example of an implicit case with the "dot" operator:

/**
 * какая-то функция, которая возвращает поле объекта name
 * @returns {String}
 */
function getName () {
  return this.name ? this.name : null;
}

var obj1 = {
  name: 'name1',
  getName: getName
}

var obj2 = {
  name: 'name2',
  getName: getName
}

// в данном случае, getName смотрит на obj1#name
console.log(obj1.getName()) // name1

// в данном случае, getName смотрит на obj2#name
console.log(obj2.getName()) // name2

I advise you to familiarize yourself with the methods for setting the function execution context in the book `Reliable JavaScript: How to Code Safely in the World's Most Dangerous Language`, it is quite clearly described there.
if you are too lazy to read the book, then look at these 2 sections: learn.javascript.ru/functions-closures and learn.javascript.ru/objects-more

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question