Paragon
Paragon

Reputation: 2722

How to Invoke anonymous javascript function on object in 1 line?

I am learning about javascript anonymous functions and scope and am trying to understand something but have become a bit stuck.

I have the following three functions:

var funcA = function (value) {
    test = value;
};

var funcB = function (value) {
    this.test = value;
};

var funcC = function (func,value) {
    var item = {};
    //single line invocation
}

I am trying to write a single line of javascript (where it says //single line invocation) such that the result of the two following calls will differ, instead of having the same effect:

funcC(funcA, "set");
funcC(funcB, "set");

Since funcB is referencing this.test instead, it makes sense that it will be changing a local (instance) value so we can make use of the "item" object in funcC. I tried doing some anonymous function "stuff" like:

item.(function(func,value){func(value)})(func, value);

However I have not had any luck in terms of the statements resulting in different outcomes. (i.e. when I run my code using node(.js) the test and this.test values both change).

Any help on understanding this better would be great.

Thanks in advance,

ParagonRG

Upvotes: 0

Views: 966

Answers (2)

Bergi
Bergi

Reputation: 665455

You can't use an anonymus function as a object property. You want to do

var item = {"f": func};
item.f(value);
// item.test == value now

right? The way JavaScript does this is the .call() function:

func.call(item, value);
// with the difference that item has no "f" property here

You can also use call with anonymous function expressions:

(function(val){ this.test = val; }).call(item, value);
// yet this equivalent looks much cleaner:
item.test = value;

Upvotes: 0

Matthew Flaschen
Matthew Flaschen

Reputation: 285047

You have to use call to tell it the instance to work on.

funcB.call(item, value);

Upvotes: 1

Related Questions