Answer the question
In order to leave comments, you need to log in
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];
}
};
var Cart = {
items = oldCart.items || {},
totalQty = oldCart.totalQty || 0,
totalPrice = oldCart.totalPrice || 0
}
this.add = function(item, id)
this.reduceByOne = function(id)
Answer the question
In order to leave comments, you need to log in
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
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question