Javascript call() function - extra parameters -
i'm reading javascript: definitive guide 6th edition
. teaches ecmascript 5. anyway, doesn't explain things thoroughly, call() function example. extent of book's definition:
any arguments call() after first invocation context argument values passed function invoked. example, pass 2 numbers function f() , invoke if method of object o, utilize code this:
f.call(o, 1, 2);
in next section author builds map
function. i've been studying ruby know how map works. question implementation using call() function. looks this:
var map = function(a,f, o) { var results = []; for(var = 0, len = a.length; < len; i++) { if (i in a) results[i] = f.call(o || null, a[i], i, a); } homecoming results; };
it defines square function , puts map use:
function square(x){ homecoming x*x; } var array = [1,2,3,4,5]; var results = map(array, square);
what purpose of i
, , a
parameters in call() function? if remove them same results.
function.call allows phone call function though method attached object.
what means can have function defined somewhere unrelated object, , can phone call function though part of object. long way of saying when utilize function.call, telling js engine utilize first parameter whenever utilize 'this' within function.
so:
function set_field_value(name, value) { // stuff this[name] = value; }
makes no sense itself, because special variable 'this' not set (meaningful) but, if utilize call, can set whatever want:
// if my_object = object: set_field_value.call(my_object, 'firstname', 'bob'); console.log(my_object.firstname); // prints 'bob'
the of import argument phone call first one, (in above case, my_object) because first argument becomes 'this' within function. rest of arguments passed 'as is' function.
so - in example, , arguments there create map function other map functions, provide array (a) , index (i) beingness worked on.
hope helps,
jay
ps - recommend book 'javascript: parts' - makes lot more sense definitive guide.
javascript
No comments:
Post a Comment