Bind function without thisArg

Sultan thysultan at gmail.com
Mon Jan 14 09:29:07 UTC 2019


The use case was to use bind to avoid closures such that "foo" is attached
to an object on demand.

var obj = {}
// some place else
obj.foo = fn.bind(, 1, 2, 3)

Where the function "fn" relies on this being the "obj" it is attached to,
this considering that calling a bound functions with:

fn.call(thisArg)

Doesn't change the thisArg.

On Mon, Jan 14, 2019 at 9:27 AM Jordan Harband <ljharb at gmail.com> wrote:

> ```
> var foo = function(a) { console.assert(this === obj) };
> var obj = { foo() { return foo.apply(this, arguments); } };
> ```
> ?
>
> On Sun, Jan 13, 2019 at 10:01 PM Ranando King <kingmph at gmail.com> wrote:
>
>> Bind is just a wrapper function provided by the engine. You can always
>> create your own:
>>
>> ```js
>> function myBind(fn, ...args) {
>>   let retval = Object.defineProperties(function(...a) {
>>     console.assert(typeof(fn) == "function");
>>     return fn(...args, ...a)
>>   }, {
>>     name: {
>>       configurable: true,
>>       value: fn.name
>>     },
>>     length: {
>>       configurable: true,
>>       value: fn.length
>>     },
>>     prototype: {
>>       configurable: true,
>>       writable: true,
>>       value: fn.prototype
>>     }
>>   });
>> }
>> ```
>>
>> This should apply your bound arguments before any arguments supplied by
>> the caller without affecting the context object.
>>
>> On Sun, Jan 13, 2019 at 11:39 PM Sultan <thysultan at gmail.com> wrote:
>>
>>> Consider the following example:
>>>
>>> var foo = (function(a) { console.assert(this === obj) }).bind(undefined,
>>> 1)
>>> var obj = {foo: foo}
>>>
>>> Calling foo from obj:
>>>
>>> obj.foo(1)
>>>
>>> Would result in an assertion. How does one go about preserving the this
>>> reference of the caller. That is i want to use .bind to only bind
>>> "arguments" and not "thisArg".
>>>
>>>
>>> _______________________________________________
>>> es-discuss mailing list
>>> es-discuss at mozilla.org
>>> https://mail.mozilla.org/listinfo/es-discuss
>>>
>> _______________________________________________
>> es-discuss mailing list
>> es-discuss at mozilla.org
>> https://mail.mozilla.org/listinfo/es-discuss
>>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.mozilla.org/pipermail/es-discuss/attachments/20190114/da198383/attachment.html>


More information about the es-discuss mailing list