我正在尝试获取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'?
谢谢!
答案 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)
您的代码中出现了一些错误和错误的假设。这就是我的感受
所以要纠正你的代码。我会建议:`
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