为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Node.js 中运行函数

如何在 Node.js 中运行函数

三国纷争 2023-03-18 16:24:22
这是我第一次在 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();
查看完整描述

1 回答

?
鸿蒙传说

TA贡献1865条经验 获得超7个赞

按照您在此处制作它的方式,它是一个范围内的功能......这意味着您无法在您尝试访问它的范围内“看到”它。


您需要使其成为“方法”或将其附加到“此”。


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


查看完整回答
反对 回复 2023-03-18
  • 1 回答
  • 0 关注
  • 58 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信