Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript [Symbol.toPrimitive](hint) to convert function

In JS functions belong to the object type. Objects can be converted to primitive types with [Symbol.toPrimitive](hint). This pure-object conversion works fine:

let obj = {
  [Symbol.toPrimitive](hint) {
    switch(hint) {
      case "string": return "all right";
      case "number": return 100;
      default: return "something else";
    }
  }
};

alert(obj); // all right
alert(+obj); // 100

However, something is wrong with function conversion:

function fun() {
  [Symbol.toPrimitive](hint) { // JS engine starts to complain here
    switch(hint) {
      case "string": return "all right";
      case "number": return 100;
      default: return "something else";
    }
  }
}

alert(fun);
alert(+fun);

What am I missing here? How do I convert function to some primitive type?

like image 762
Simonas Avatar asked Nov 17 '25 23:11

Simonas


2 Answers

You need to address the function's Symbol.toPrimitive property and assign a function.

Otherwise you take an array with a symbol and try to call a function with it, which not exists.

function fun() {
}

fun[Symbol.toPrimitive] = function (hint) {
    switch(hint) {
        case "string": return "all right";
        case "number": return 100;
        default: return "something else";
    }
};

console.log(fun);
console.log(+fun);
like image 126
Nina Scholz Avatar answered Nov 20 '25 13:11

Nina Scholz


The inside of the { block after function(...){ has to be the function body only. To assign to a property of the function object, you have to do that after the function has been declared:

function fun() {
}
fun[Symbol.toPrimitive] = function(hint){ // JS engine starts to complain here
  switch(hint) {
    case "string": return "all right";
    case "number": return 100;
    default: return "something else";
  }
};

console.log(fun);
console.log(+fun);
like image 44
CertainPerformance Avatar answered Nov 20 '25 13:11

CertainPerformance



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!