簡體   English   中英

JavaScript一個函數,它在每次調用時返回一個變化的值

[英]JavaScript a function that returns a changing value on every call

我正在嘗試編寫一個函數,當被調用時將返回考慮之前調用它的函數。 我是JavaScript的新手,所以我只想確保它可以完成。 我想將變化的值存儲在一個可變變量中。

var formatPrint = function(orig, changed){
    return "Started with "+orig+" now is "+changed; 
}

var adder = function(orig){
        var changed = orig;
        return function(){return printer(orig, (changed+5))};
}

我正在調用函數如下:

var orig10 = adder(10);
orig10();

從10開始的返回現在是15

orig10();

從10開始的返回現在是15

orig10();

從10開始的返回現在是15

應該返回返回開始時10現在是15返回開始時10現在是20返回開始時10現在是25

抱歉,如果我的代碼應該輸入到論壇中,我就會遇到問題。 我是個小伙子..感謝您的幫助

+ =怎么樣?

var adder = function(orig){
    var changed = orig;
    return function(){return printer(orig, (changed+=5))};
}

實例: http//jsfiddle.net/3T72G/

閱讀你的問題和評論,似乎你正在嘗試創建某種class ,您可以使用它來執行某些數學函數,並在請求時格式化特定的字符串。 如果是這樣,那么你可能正在尋找這樣的事情。

使用Javascript

function MyConstructor(orig) {
    this.orig = this.current = orig;
}

MyConstructor.prototype.toString = function () {
    return "Started with " + this.orig + " now is " + this.current;
};

MyConstructor.prototype.add = function (value) {
    this.current += value;

    return this;
};

MyConstructor.prototype.subtract = function (value) {
    this.current -= value;

    return this;
};

MyConstructor.prototype.multiply = function (value) {
    this.current *= value;

    return this;
};

MyConstructor.prototype.divide = function (value) {
    this.current /= value;

    return this;
};

MyConstructor.prototype.mod = function (value) {
    this.current %= value;

    return this;
};

var orig10 = new MyConstructor(10);

console.log(orig10.toString());
orig10.add(5).multiply(5).mod(2);
console.log(orig10.toString());

產量

Started with 10 now is 10
Started with 10 now is 1

jsFiddle上

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM