Javascript: passing a special argument

I remember how I came across a solution to this problem. There is a special term for this type of argument, if I'm not mistaken. But I just can’t remember exactly what it is. I try to find it on the Internet, but to no avail. So here it is:

I want to pass an argument consisting of a function. What should I do?

function meow(cat){
    var z = $("#nyan").position().cat;
    alert(z);
}

meow(left);

or

function meow(cat){
    var z = $("#nyan").cat();
    alert(z);
}

meow(height);
+3
source share
3 answers

This is not quite a function; it looks more like you want a property name.

I'm just going to give you some tips and see which one you like best.

function meow(cat) {
    var z = $("#nyan").position()[cat];
    alert(z);
}

meow("left");

... or...

function meow(cat) {
    var z = $("#nyan")[cat]();
    alert(z);
}

meow("height");

... or, indeed, using the function:

function meow(getter) {
    var z = getter($("#nyan"));
    alert(z);
}

meow(function(nyan) { return nyan.position().left });
meow(function(nyan) { return nyan.position().top });
// etc.

: , a.b a["b"] - .

, a.x, width true a.y, width false, :

var result = a[width ? "x" : "y"];
0

call , :

function meow(cat) {
    var z = cat.call($("#nyan"));
    alert(z);
}

meow($.fn.height);
0

These solutions will work, but they will not work if you want the function to accept both a property / attribute and functions.

Try the following:

function meow(cat){
  var z = typeof cat == 'function' ? $("#nyan").[z]() : $("#nyan")[z];
  alert(z);
}

meow(left);

Change this to suit your needs.

0
source

All Articles