如何在 Node.js 中运行函数

这是我第一次在 Node.js 中创建类,我想知道为什么我不能运行这个函数……有人能给我指出正确的方向吗?


class Customer {

  constructor() {

    this.shoppingBasket = [];


    function startShopping() {

      const prompt = require("prompt-sync")();

      const itemName = prompt("What item is this?");

      const itemPrice = prompt("How much is it?");

      const taxExemption = promt("Is this a food, book or medical product?");

      console.log(`Your item is ${itemName}`);

    }

  }

}


Customer = Customer;

Customer.startShopping();


三国纷争
浏览 63回答 1
1回答

鸿蒙传说

按照您在此处制作它的方式,它是一个范围内的功能......这意味着您无法在您尝试访问它的范围内“看到”它。您需要使其成为“方法”或将其附加到“此”。// We normally require/import things at the top, but not nessesarily.// const PromptSync = require("prompt-sync");class Customer {  constructor() {    this.shoppingBasket = [];    this.startShoppingPropertyFunction = () => {      // If imported at top, use this instead:      // const prompt = new PromptSync();      const prompt = require("prompt-sync")();      const itemName = prompt("What item is this?");      const itemPrice = prompt("How much is it?");      const taxExemption = prompt("Is this a food, book or medical product?");      console.log(`Your item is ${itemName}`);    }  }  startShoppingMethod() {    // If imported at top, use this instead:    // const prompt = new PromptSync();    const prompt = require("prompt-sync")();    const itemName = prompt("What item is this?");    const itemPrice = prompt("How much is it?");    const taxExemption = prompt("Is this a food, book or medical product?");    console.log(`Your item is ${itemName}`);  }}const myCustomer = new Customer();myCustomer.startShoppingMethod();myCustomer.startShoppingPropertyFunction();
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript