如何访问Closures保留的变量?

时间:2018-01-18 22:10:47

标签: javascript closures

我正在尝试获取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'从函数外部访问'author'和'title'?

谢谢!

3 个答案:

答案 0 :(得分:2)

在函数上使用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

答案 1 :(得分:2)

您的代码中出现了一些错误和错误的假设。这就是我的感受

  • 没有使用语法来定义新对象。
  • 当您从对象返回一个函数时,该对象会松散其内部结构并仅返回该函数。 即 MyBooks {作者:'托尔金',标题:'霍比特人' } [function:addPrice]
  • 金额变量不是闭包,而是使用 this.amount 将其值存储在对象内存中。

所以要纠正你的代码。我会建议:`

        function MyBooks(author, title){
        this.author = author;
        this.title = title;
        this.amount = 0;

        this.addPrice = function(amount){

            return this.amount += amount;
        }

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

答案 2 :(得分:1)

您还可以使用Class和构造函数:

class MyBooks {
  constructor(author, title) {
    this.author = author;
    this.title = title;
  }

  setAmount(value) {
    this.amount = value;
  }

  getAmount() {
    return this.amount;
  }

}

var MyBooksObj= new MyBooks('Tolkin','Hobbit');
MyBooksObj.setAmount('100 dollars');
 alert(MyBooksObj.getAmount()); //outpout: 100 dollars
 alert("author: " + MyBooksObj.author); //outpout: author: Tolkin
 alert("title: " + MyBooksObj.title); //outpout: title: Hobbit

更多详情:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes

同样有趣:https://coryrylan.com/blog/javascript-es6-class-syntax