I was trying to implement the Function.call
without using call in any form. The idea was to create an object whose this
is the value passed as thisArg
to the call method. Initially Object.create(thisArg)
came to mind, however that doesn't really work since it only sets the prototype of the object to thisArg
.
The answer basically boils down to using Object()
constructor, and then setting the function with arguments as a 'method' on some key for that object.
Something along this lines:
thisArg = thisArg || window;
thisArg = Object(thisArg);
const methodSymbol = Symbol();
thisArg[methodSymbol] = this; // this is the function on which call is executed.
My query is that I am a bit confused on the working of the Object constructor - it seems it sets the this
of the object method to the value passed in the constructor, but there is some other malarkey in the spec/MDN docs that basically confuses me.
Is there a better explanation on why this works? any other way to implement the same? maybe this is some hacky JS workings that I am not aware of.
I was trying to implement the Function.call
without using call in any form. The idea was to create an object whose this
is the value passed as thisArg
to the call method. Initially Object.create(thisArg)
came to mind, however that doesn't really work since it only sets the prototype of the object to thisArg
.
The answer basically boils down to using Object()
constructor, and then setting the function with arguments as a 'method' on some key for that object.
Something along this lines:
thisArg = thisArg || window;
thisArg = Object(thisArg);
const methodSymbol = Symbol();
thisArg[methodSymbol] = this; // this is the function on which call is executed.
My query is that I am a bit confused on the working of the Object constructor - it seems it sets the this
of the object method to the value passed in the constructor, but there is some other malarkey in the spec/MDN docs that basically confuses me.
Is there a better explanation on why this works? any other way to implement the same? maybe this is some hacky JS workings that I am not aware of.
The Object
constructor when called without new
will
null
or undefined
, returns a plain object (like calling new Object()
or just using {}
)
console.log( typeof Object("hello") ); // "object"
console.log( Object("hello") instanceof String ); // true
console.log( typeof Object(42) ); // "object"
console.log( Object(42) instanceof Number ); // true
The object constructor without new
is used when you absolutely need an object, rather than any other primitive. For the line thisArg[methodSymbol] = this;
you cannot use it with primitives, because you cannot change any of their properties. But you can if the value was capital String, Number, Boolean, etc.