[英]Trying to wrap this function in an object
Sorry for being vague and confusing everyone, Im grateful for all the feedback but let me explain what i am trying to do. 很抱歉给大家带来含糊不清的信息,不胜感激,感谢所有反馈,但让我解释一下我要做什么。
I want to create an object called Multiplier with two methods: multiply and getCurrentValue multiply should initially return the number supplied * 1 and from then on whatever the current value is times the number supplied, getCurrentValue should return the last answer returned from multiply. 我想用两种方法创建一个称为Multiplier的对象:乘法和getCurrentValue乘法应首先返回提供的数字* 1,然后从当前值乘以提供的数字乘以,getCurrentValue应该返回从乘法返回的最后一个答案。
Hey everyone I am having a little trouble grasping this concept. 大家好,我在理解这个概念时遇到了一些麻烦。
Here is my code so far: 到目前为止,这是我的代码:
var multiplier = {
function multiply(){
alert("Input a number to be multiplied by 1")
var a = prompt("Input your desired number");
var b = a * 1;
return alert(b);
}
}
multiply();
any help or further explaining on how i would go about this would be appreciated 任何帮助或进一步解释我将如何做到这一点将不胜感激
var multiplier = {
lastValue: null,
getCurrentValue: function() {
return lastValue;
},
multiply: function() {
alert("Input a number to be multiplied by 1")
var a = prompt("Input your desired number");
var b = a * 1;
lastValue = b;
return alert(b);
}
}
This should do what you want. 这应该做您想要的。 You're defining an object named multiplier, that has two functions and a variable to save the last value.
您正在定义一个名为multiplier的对象,该对象具有两个函数和一个用于保存最后一个值的变量。
Of course, there are other ways to accomplish this, but your question is a little vague. 当然,还有其他方法可以完成此操作,但是您的问题有点含糊。
A more object oriented approach would be like so. 更加面向对象的方法就是这样。
function Multiplier() {
var lastValue = null;
this.getCurrentValue = function() {
return lastValue;
};
this.multiply = function() {
alert("Input a number to be multiplied by 1");
var a = prompt("Input your desired number");
var b = a * 1;
lastValue = b;
return alert(b);
}
}
With this approach, your lastValue variable is private. 使用这种方法,您的lastValue变量是私有的。 You've only exposed the two functions.
您仅公开了这两个功能。 Now you can create a new one of these objects whenever you need one, like so.
现在,您可以在需要时创建一个新的对象,就像这样。
var myMultiplier = new Multiplier();
And you can call functions on that multiplier like so. 您可以像这样在乘数上调用函数。
myMultiplier.multiply();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.