Javascript 在本代码中,这指的是什么?

Javascript 在本代码中,这指的是什么?,javascript,Javascript,我是编程新手,这是来自tutsplus的教程。 在本代码中,本指的是什么 function addToCart(price) { if (this.total) { this.total = 0; } this.total += price; return this.name + '\'s cart total is £' + this.total; } 你上面发布的代码在我看来不是100%正确。我想,图坦卡蒙教程的思想是教你Javascr

我是编程新手,这是来自tutsplus的教程。 在本代码中,
指的是什么

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

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

你上面发布的代码在我看来不是100%正确。我想,图坦卡蒙教程的思想是教你Javascript面向对象编程的基础知识

我使用上面的示例在这里创建了一个带注释的JSFIDLE。我希望这有助于回答你的问题

以下是上述小提琴中的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);
}

研究和学习javascript的基础知识将回答您的问题。这就是学习教程的原因,对吗?如果你不知道如何搜索,请搜索
javascript这个关键字
。Stackoverflow不是一个帮助论坛,它更像是一个问答式的百科全书。如果你不能用一种通用的方式来表达你的问题,一旦回答了,对每个人都有用,那么这里就不是提问的地方。特别是当你不知道你要问的语言的基本知识时。我同意前面的评论。你的问题应该有一个特定的问题,而你的帖子中既没有。