javascript 警报显示代码而不是字符串

标签 javascript

首先,我是 JavaScript 和编码新手。其次,我正在使用 JavaScript 编写一个书店项目,并带有一条显示每个客户的总因子的警报消息。但警报消息显示了我的函数“printFactor”的代码,其中插入了该函数生成的字符串。这是我的代码:

   function Book(name, writer, date, price) 
   {
     this.name = name;
     this.writer = writer;
     this.date = date;
     this.price = price;
   }

   function Customer(name, gender, turn)
   {
     this.name = name;
     this.gender = gender;
     this.turn = turn;
     this.numberOfBooks = 0;
     this.totalSum = 0;
     this.bookList = [new Book("-", "-", "-", 0)];


      //Functions.
      this.addBook = function (newBook) {
      this.numberOfBooks++;
      this.bookList.push(newBook);
      };

      this.printFactor = function () {
         var message = "";

         if (this.numberOfBooks === 0) {
             message = "No Books Has Been Added to Book List!";
             return (message);
         }

         else {
             message = this.name + "    " + this.gender + "    Number of Books: " + this.numberOfBooks + "    Customer's Turn: " + this.turn + "\nBooks:\n";

             var i;
             var newMessage;
             for (i = bookList.length - 1; i > 0; i--) {
                 newMessage = bookList[i].name + "    " + bookList[i].writer + "    " +  bookList[i].date + "    " + bookList[i].price.toString() +"\n" ;
              message += newMessage;
                 this.totalSum += bookList[i].price;
                 this.bookList.pop();
            }

              newMessage = "Total Sum: " + this.totalSum;
              message += newMessage;

              return (message);
    }
};
}

  var book = new Book("Faramarz Bio", "Faramarz Falsafi Nejad", "1377/04/29",  13000);

  var faramarz = new Customer("faramarz", "Male", 3);

  faramarz.addBook(book);
  faramarz.addBook(book);
  faramarz.addBook(book);
  faramarz.addBook(book);


  var m = faramarz.printFactor;


  window.alert(m);

最佳答案

您需要调用该函数:

var m = faramarz.printFactor();

关于javascript 警报显示代码而不是字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53708526/

相关文章:

javascript - 在弹出之前删除警告框

javascript - 按类型使用最低的节点数据

php - 我怎样才能在php中创建一个接口(interface)来添加数据csv文件

javascript - 模拟与导入然后模拟

javascript - lambda : filter by "fuzzy search"

javascript - 如何缓存/预先计算某些东西(没有全局变量)?

javascript - XMPP onRoster 名称属性未出现

javascript - 使用 localStorage 代替 Cookies 有什么缺点吗?

Javascript 文本操作

javascript - 使用 react-router v4 添加或更新查询参数而不重新渲染主组件