Javascript 如何在Node.js中运行函数
这是我第一次在Node.js中创建类,我想知道为什么我不能运行这个函数。。。。有人能给我指出正确的方向吗Javascript 如何在Node.js中运行函数,javascript,node.js,oop,Javascript,Node.js,Oop,这是我第一次在Node.js中创建类,我想知道为什么我不能运行这个函数。。。。有人能给我指出正确的方向吗 class Customer { constructor() { this.shoppingBasket = []; function startShopping() { const prompt = require("prompt-sync")(); const itemName = prompt("What it
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();
这是一个范围函数,就像你在这里做的那样。。。这意味着您无法在试图访问它的范围内看到它 您需要使其成为一个方法,或者将其附加到此方法
// 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();
startShopping是构造函数中的一个免费函数-您必须将其移出;应该是让客户=新客户;并将函数从构造函数移动到类BodyCustomer,因为Customer没有属性startShopping。该函数仅在构造函数内部可见。但是你的代码还有很多奇怪的地方。我建议首先阅读更多关于课程的内容: