javascript2016 javascript2016 - 5 months ago 8
Javascript Question

How to use an object passed to a fun as context for inner function?

I am iterating through an array of functions and am suppose to call each function USING THE OBJECT AS THE CONTEXT and I don't know how to do it - tried apply but it doesn't work-I guess because I don't fully understand this, apply etc.
Happy about some help!

function calling(obj,arr){
for (var i=0; i<arr.length;i++){
arr[i].apply(null,obj);
}
return arr;
}

var fnA = [
function () {
this.yes = true;
},
function () {
this.no = false;
}
];
var obj = {};

calling(obj, fnA);
obj.yes; //should return true

Answer

Are you sure you read the documentation of Function.prototype.apply() correctly?

thisArg, which sets the execution context, is the first parameter of apply, not the second:

arr[i].apply(obj);

As second parameter, you can optionally pass an array of arguments that the function should be called with.

Comments