javarwx
javarwx

Reputation: 1

How to use the "this" keyword to call a

How do I write a function in JavaScript that receives an array and a function(convertFunc). The function calls convertFunc for every element of the array. The element should be accessed via the this keyword. The function should return an array of the return values of the convertFunc calls? e.g.

function(array, convertFunc() {  // array=[1,2,3]
    return this+10;
} 

Should return [11,12,13]

Thanks

Upvotes: 0

Views: 124

Answers (4)

Joe Johnson
Joe Johnson

Reputation: 1824

var myFunc = function(fn) {  // array=[1,2,3]
    return fn(this);
};

myFunc.call(arr,function convertFunc(){
    return this+10;
});

But, to solve your exact problem:

var arr = [1,2,3], addTen = function(){
    for (var l=this.length;l--;) this[l] += 10;
};

addTen.call(arr);

Upvotes: 0

kiranvj
kiranvj

Reputation: 34117

Try this if you are looking for extending the Array object

Array.prototype.convertFunc = function() {

var arr = this, i; // As you want array is access using the this keyword.

for(i = 0; i<arr.length; i++)
{
    arr[i] = arr[i] + 10;
}

return arr;
}

var myArray = [1,2,3];


 // Call like this
 myArray.convertFunc();

Fiddle here http://jsfiddle.net/PYxzj/

Update

And to answer your question try this

    // Pass your array and a function as parameter
function arrayModify(array, convertFunc)
{
  return array.convertFunc();
}


// This function iterates your array and adds 10 to each element.
var arrayAddFunction = function() {

   var arr = this, i;
   for(i = 0; i<arr.length; i++)
   {
      arr[i] = arr[i] + 10;
   }

return arr;
}

// Extending the array object
Array.prototype.convertFunc = arrayAddFunction;

var aa = [1,2,3];

// As you want send your array and a function as parameters to another function 
alert(arrayModify(aa,arrayAddFunction)); // -> [11, 12, 13]

Fiddle here http://jsfiddle.net/qzB4e/

Upvotes: 0

Niko
Niko

Reputation: 26730

  1. Create the function, e.g. function map(arr, convertFunc) {
  2. Iterate over all elements of the array arr.
  3. Tip: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/call
  4. Return an array containing all results from the function calls.
  5. }

Figure the exact details out by yourself, good luck :)

Upvotes: 2

Dan Barzilay
Dan Barzilay

Reputation: 4983

array.map(callback[, thisObject]); might fit for you.

Example:

var nums = [1,2,3];

function FuncName(x)
{
    return x+10;
}

var result = nums.map(FuncName); //[11,12,13]

Upvotes: 0

Related Questions