JavaScript警报显示由字符串插入的代码

时间:2018-12-10 15:14:42

标签: 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);

4 个答案:

答案 0 :(得分:1)

您需要调用该函数:

var m = faramarz.printFactor();

答案 1 :(得分:1)

变量m同样包含对该函数的引用,但是您需要调用它以获得结果。

var m = faramarz.printFactor();

window.alert(m);

答案 2 :(得分:1)

您根本不调用函数,这应该可以工作。 var m = faramarz.printFactor()

除了您引用一个不存在的变量“ booklist”,它应该是“ this.booklist”

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

答案 3 :(得分:1)

您需要通过在末尾添加()来实际调用该函数,如下所示:

var m = faramarz.printFactor()