我正在尝试获取Closures保留的变量。我不确定那是否可能。

这是我的代码:

function MyBooks (author, title){

      this.author = author;
      this.title = title;

      return function addPrice(amount){

          return amount;
      }

 }
 var MyBooksObj=MyBooks('Tolkin','Hobbit');
 alert(MyBooksObj('100 dollars')); //outpot: 100 dollars
 alert("author: " + MyBooksObj.author); //outpot: author: undefined
 alert("title: " + MyBooksObj.title); //outpot: title: undefined


有人知道如何使用变量“ MyBooksObj”从函数外部访问“作者”和“标题”吗?

谢谢!

最佳答案

在函数上使用new运算符会创建一个新对象,并在结果上绑定“ this”。



function MyBooks (author, title){

      this.author = author;
      this.title = title;

      this.addPrice= function (amount){

          return amount;
      }

 }
 var MyBooksObj= new MyBooks('Tolkin','Hobbit');
 alert(MyBooksObj.addPrice('100 dollars')); //output: 100 dollars
 alert("author: " + MyBooksObj.author);     //output: auther: Tolkin
 alert("title: " + MyBooksObj.title);       //output: title: Hobbit

关于javascript - 如何访问Closures保留变量?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48331152/

10-11 23:58
查看更多