Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
401 views
in Technique[技术] by (71.8m points)

doubts on javascript apply - function memoization

I'm struggling with an example of js memoization found on a book, here's the code:

Function.prototype.memoized = function(key){
    this._values = this._values || {};
    return this._values[key] !== undefined ? this._values[key] : this._values[key] = this.apply(this, arguments);
}

here's a fiddle with a complete example

what I don't really get is how this piece of code works and what it does, in particular the apply part:

return this._values[key] !== undefined ? this._values[key] : this._values[key] = this.apply(this, arguments);

I know and understand how apply works

The apply() method calls a function with a given this value and arguments provided as an array

suppose that this._values[key] is equal to undefined, then the returned value will be this.apply(this, arguments): does this code re-launch the memoized function? I've tried to add some logs inside the function to see how many times the function is called, but it seems it's been launched only once..

Can anyone please give me a hint? It's probably a dummy question, please be patient, thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's use a simple example, fibonacci numbers.

function fib(n) {
    if (n < 2) return 1;
    return fib.memoized(n-1) + fib.memoized(n-2);
}

Here we can see that the memoized method is applied on the fib function, i.e. your this keyword refers to the fib function. It does not relaunch the memoized function, but "launches" the function on which it was called. However, it does call it with this set to the function itself, which does not make any sense. Better:

Function.prototype.memoize = function(key){
    if (!this._values)
        this._values = {};
    if (key in this._values)
        return this._values[key];
    else
        return this._values[key] = this.apply(null, arguments);
// pass null here:                            ^^^^
}

Even better would be if memoized would return a closure:

Function.prototype.memoized = function(v) {
    var fn = this, // the function on which "memoized" was called
        values = v || {};
    return function(key) {
        if (key in values)
            return values[key];
        else
            return values[key] = fn.apply(this, arguments);
    }
}
var fib = function(n) {
    if (n < 2) return 1;
    return fib(n-1) + fib(n-2);
}.memoized();
// or even
var fib = function(n) { return fib(n-1) + fib(n-2) }.memoized({0:1, 1:1});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...