-10

I am new to programming and this is from a tutorial from tutsplus. In this code what does this refer to?

function addToCart(price) {
    if (this.total) {
        this.total  = 0;
    } 

    this.total += price;
    return this.name + '\'s cart total is £' + this.total;
}
Gary Kerr
  • 11,462
  • 2
  • 43
  • 49
  • Research and learning the basics of javascript will answer your question. It's the reason for tutorials right? – NewToJS Jan 19 '17 at 02:05
  • 2
    If you don't know how to search it, search for `javascript this keyword`. – GramThanos Jan 19 '17 at 02:07
  • Stackoverflow isn't a help forum, it's more of a Q&A style encyclopedia. If you can't present your problem in a generic way that, once answered, could be useful to everyone, then this isn't the place to ask. Especially when you don't know the basics in the language you're asking about. – Domino Jan 19 '17 at 02:08
  • I agree with the previous commenters. Your question should have a specific question or issue, and your post contains neither. – Joshua Briefman Jan 19 '17 at 02:16

1 Answers1

-1

The code you've posted above doesn't look 100% correct to me. The idea of the Tut's tutorial, I'm assuming, is to teach you Javascript Object Oriented Programming basics.

I've created a commented JSfiddle here, using your above example. I hope this helps a little bit to answer your question.

https://jsfiddle.net/iamjpg/vtndfL1y/

Here is the JS inside the above fiddle:

// Define function which will be our Object
function cart(name) {

    // Define a name for cart. Default to 'Bob' if undefined.
    this.name = name || 'Bob';

  // addToCart method on object.
  this.addToCart = function(price) {

    // If there is no total, set the total to zero.
    if (!this.total) {
      this.total = 0;
    }

    // Increment total by passed in price parameter
    this.total += price;

    // Return the string containing the total value.
    return this.name + '\'s cart total is £' + this.total;
  }
}

// Construct cart object
var cart = new cart('Mario');

// Set event listener on the button.
document.getElementById('cart_button').onclick = function() {

  // On each click, update the cart price incrementing by 5.
  document.getElementById('price').innerHTML = cart.addToCart(5);
}
iamjpg
  • 5,134
  • 1
  • 13
  • 17