0

I need help explanation of this script

var test = {
    property_1 : 'aaa',
    property_2 : 'bbb'
}

var place = function(str, ph){
    return test[ph];
}

What is the meaning of definition place and what will be return type of that function?
I can't understand from where is parameter str and ph come?

Here is the screenshot tutorial i read that do this at line 19

enter image description here

Thank you.

GusDeCooL
  • 5,639
  • 17
  • 68
  • 102

2 Answers2

3

What is the meaning of definition place?

Functions are first class in JavaScript. They can be assigned as values for variables.

You can then invoke that variable place, which will invoke the function it points to (its value).

What will be return type of that function?

In could be anything. Most likely it will be a string or undefined.

I can't understand from where is parameter str and ph come?

They would be passed like so...

place(1, 2);

In your example, the first argument seems to be superflous as it's not used in the function's body.

alex
  • 479,566
  • 201
  • 878
  • 984
  • i'm sorry. i can't understand what you mean. Did you mean declaration variable `place` above is not valid? – GusDeCooL Sep 02 '12 at 13:14
  • I added screenshot tutorial that do this. but still can't wondering where is the parameter passed like your example. – GusDeCooL Sep 02 '12 at 13:21
  • 1
    @GusDeCooL: The `place` declaration is perfectly valid. You can assign functions to variables (`var func = function() {...};`) the same way as you can assign other values to variables, such as strings, arrays, etc (`var someString = "foo";`). It's the same thing. `func` points to a function and `someString` points to a string. Maybe you find it helpful the read the MDN JS guide about functions: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Functions. – Felix Kling Sep 02 '12 at 13:26
2

place is a function. Its return type is typeof test[ph], which is a string. It's similar to the following:

function place (str, ph) {
  return test[ph];
}

The parameters str and ph need to be passed to the function when you invoke it:

place("foo", "property_1");

EDIT: The second argument of String.replace() can be a function. Thus, when you call html.replace(searchPattern, placeholderReplacer), internally, replace will invoke placeholderReplacer with the parameters str and ph, which represent the matched substring, and the first matched capturing group, respectively.

References:

Community
  • 1
  • 1
João Silva
  • 89,303
  • 29
  • 152
  • 158