在这段代码中,这是指什么?

时间:2017-01-19 02:01:59

标签: javascript

我是编程新手,这是来自tutsplus的教程。 在此代码中this引用了什么?

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

    this.total += price;
    return this.name + '\'s cart total is £' + this.total;
}

1 个答案:

答案 0 :(得分:-1)

您上面发布的代码对我来说并不是100%正确。我假设,Tut教程的想法是教你Javascript面向对象编程基础。

我在这里使用上面的例子创建了一个评论过的JSfiddle。我希望这有助于回答你的问题。

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

以上是小提琴里面的JS:

// 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);
}