A Dude
A Dude

Reputation: 187

Transform a Javascript Object to Function manually

I am currently learning Javascript. I've read that an object which has an internal member [[Call]] produces function as the result of typeof that object. I wonder whether I can set this internal member in my Javascript code, i.e. is something like this possible? :

function my_foo(){}

var my_obj = {};  // is the ';' an empty statement?

my_obj["[[Call]]"]=my_foo; // in my test, this didn't work

And if it is possible, would this change the result of typeof that object from object to function?

Upvotes: 7

Views: 155

Answers (1)

T.J. Crowder
T.J. Crowder

Reputation: 1075735

I've read that an object which has an internal member [[Call]] produces function as the result of typeof that object. I wonder whether I can set this internal member in my Javascript code, i.e. is something like this possible?

No. You cannot directly set or modify internal slots of JavaScript objects. That's part of why they're internal slots, not properties. Your code just creates a property called [[Call]], which is unrelated to the internal slot. From the linked spec section:

Internal slots correspond to internal state that is associated with objects and used by various ECMAScript specification algorithms. Internal slots are not object properties and they are not inherited. Depending upon the specific internal slot specification, such state may consist of values of any ECMAScript language type or of specific ECMAScript specification type values. Unless explicitly specified otherwise, internal slots are allocated as part of the process of creating an object and may not be dynamically added to an object. Unless specified otherwise, the initial value of an internal slot is the value undefined. Various algorithms within this specification create objects that have internal slots. However, the ECMAScript language provides no direct way to associate internal slots with an object.

There's no mechanism defined to let you set [[Call]]. (This isn't universally true of all internal slots; for instance, there's a mechanism that lets you set the [[Prototype]] internal slot of an object: Object.setPrototypeOf. But there isn't one for [[Call]].)

Upvotes: 8

Related Questions