JavaScript clarification and features

I read Ninja JavaScript Secrets , and I saw this code that causes function overloading:

function addMethod(object, name, fn)
{
        var old = object[name];
        object[name] = function ()
        {
                if(fn.length == arguments.length) return fn.apply(this, arguments)
                else if(typeof old == 'function') return old.apply(this, arguments);
        };
}

function Ninjas()
{
        var ninjas = ["Dean Edwards", "Sam Stephenson", "Alex Russell"];
        // addMethod is defined in Listing 2-28
        addMethod(this, "find", function ()
        {
                return ninjas;
        });
        addMethod(this, "find", function (name)
        {
                var ret = [];
                for(var i = 0; i < ninjas.length; i++)
                if(ninjas[i].indexOf(name) == 0) ret.push(ninjas[i]);
                return ret;
        });
        addMethod(this, "find", function (first, last)
        {
                var ret = [];
                for(var i = 0; i < ninjas.length; i++)
                if(ninjas[i] == (first + " " + last)) ret.push(ninjas[i]);
                return ret;
        });
}

var ninjas = new Ninjas();


assert(ninjas.find().length == 3, "Finds all ninjas");
assert(ninjas.find("Sam").length == 1, "Finds ninjas by first name");
assert(ninjas.find("Dean", "Edwards").length == 1, "Finds ninjas by first and last name");
assert(ninjas.find("Alex", "X", "Russell") == null, "Does nothing");

function assert(a,b)
{
  if (a==true) console.log(b) ; else console("----");
}

As far as I understand, it addMethodalways saves the value of the oldfunction (through closure).

So finally, there is one function that checks the condition, and if it fails, it calls the function old, which in turn does the same.

However, I do not understand the assessment arguments.length(I know the differences between function().lengthand argument.length).

Which rectangle refers argumentsto?

enter image description here

I tracked it in the debugger and I got confused because the function first logs (so it arguments.lengthis 3 [(object, name, fn)], but later it is called so that now there is one more argument.

How it works?

JSBin

+5
1

: ( ?)

- object[name] = function ()

arguments function. arguments function s, addMethod(object, name, fn), , .


, (fn.length), , (arguments.length), 1- . :

ninjas.find()                       // (0 == 0), uses `function ()`
ninjas.find("Sam")                  // (1 == 1), uses `function (name)`
ninjas.find("Dean", "Edwards")      // (2 == 2), uses `function (first, last)`
ninjas.find("Alex", "X", "Russell") // (? == 3), no match, returns `undefined`
+5

All Articles