Nested .bind not working as expected - javascript

Unfortunately .bind has been giving me grief when creating more complex closures.
I am quite interested in why .bind seems to work differently once you nest functions.
For example :
function t(){
t = t.bind({}); //correctly assigns *this* to t
function nested_t(){
nested_t = nested_t.bind({}); // fails to assign *this* to nested_t
return nested_t;
}
return nested_t();
}
//CASE ONE
alert(t());
// alerts the whole function t instead of nested_t
//CASE TWO
aleft(t.call(t));
// alerts the global object (window)
In both cases I was expecting a behavior like this:
function t(){
var nested_t = function nested_t(){
return this;
};
return nested_t.call(nested_t);
}
alert(t.call(t));
If someone could explain the behavior of .bind in the first (and/or) second case it would be much appreciated!

So, i'm not entirely reproducing your issue here (both cases return the global object), but i'll try and explain the code as i see it.
function t(){
t = t.bind({}); //correctly assigns *this* to t
function nested_t(){
nested_t = nested_t.bind({}); // fails to assign *this* to nested_t
return this;
}
return nested_t();
}
//CASE ONE
alert(t());
Let's take it step by step.
First, the function t() is defined. Then, upon call, it gets overwritten with a clean context. However, i don't see any usage of this context.
Now, a nested function (nested_t) is defined. Upon call, it is overwritten with a clean context. It then returns the context it had when it was called.
Back to t(). You then return the result of nested_t(), not nested_t itself. In the original function call, nested_t is still being called with global context.
Therefore, when you run t(), it returns the global object.

How your code works
It's very unclear, what your code is trying to do. You can find the documentation for .bind() here. It looks like you might be somehow misunderstanding what this is and how to use it. Anyway, what happens when you run your code is this:
A t function is created in global scope.
[case one] The t function is called.
Global scope t is replaced with a new value (original t bound to a specific context - anonymous empty object), which doesn't affect the current call in any way. Also, while the global t is overwritten, the local t is behaving as read-only. You can check it out by trying the following code: (function foo () { return (function bar () { bar = window.bar = 'baz'; return bar; })(); })() and comparing return value with window.bar.
The same thing happens with nested_t in the nested context (instead of global context).
Result of nested_t call is returned. nested_t returns the context it was called with, which was window, as no context was specified. Specifically, it was not called with an empty object context, because the .bind() inside didn't affect the call itself.
[case two] The exact same thing happens once again. Now you're just calling t with itself as context. Since t doesn't use its context (this) anywhere in its code, nothing really changes.
What your misconceptions might be
Basically, you're mixing up two things - function instance and function call context. A function is a "first-class citizen" in JavaScript - it's an object and you can assign values to its properties.
function foo () {
foo.property = 'value';
}
foo(); // foo.property is assigned a value
This has nothing to do with function call context. When you call a function a context is assigned to that call, which can be accessed using this (inside function body)
function foo () {
this.property = 'value';
}
var object = {};
foo.call(object); // object.property is assigned a value
When you use .bind(), you just create a new function with the same code, that is locked to a specific context.
function foo () {
this.property = 'value';
}
var fixedContext = {},
object = {};
bar = foo.bind(fixedContext);
foo.call(object); // fixedContext.property is set instead of object.property
But in this case, there are also function instances foo and bar, which can also be assigned properties, and which have nothing to do with contexts of calls of those functions.

Let's look at how bind works. First, one level of nesting:
var foo = function() { return this.x; };
alert(foo()); // undefined
alert(foo.bind({x: 42})()); // 42
Now we can add the next level of nesting:
var bar = function() { return foo.bind(this)(); };
alert(bar()); // undefined
alert(bar.bind({x: 42})());
We pass our this context to foo with - guess what? - bind. There is nothing different about the way bind works between scopes. The only difference is that we've already bound this within bar, and so the body of bar is free to re-bind this within foo.
As a couple of commenters have noted, functions that overwrite themselves are a huge code smell. There is no reason to do this; you can bind context to your functions when you call them.
I highly, highly recommend reading the documentation on bind, and trying to understand it to the point where you can write a basic version of Function.prototype.bind from scratch.

Related

Are IIFEs in JavaScript recursive?

I am passing a function as an argument to a constructor within an IIFE. I realize that the outer function of an IIFE is going to be executed, but it appears the function argument is also executed. I don't really understand why and am wondering how to work around this problem. Here are two examples:
var Foo = function(bar) {
this.bar = bar;
};
new Foo(function() { console.log("test"); });
In the above example, things work as I'd expect. The anonymous function is passed as an argument to the Foo constructor, but is not run.
Here's another example, where it appears an anonymous function that is created within an IIFE is executed, even though it is not explicitly called:
(function() {
var Foo = function(bar) {
this.bar = bar;
};
Foo.STATIC_FIELD = new Foo(new function() { console.log("test"); });
return Foo;
})();
In this second example, "test" is written to the console. I am using the IIFE to protect the global name space from polluting it with Foo. However, I do not want the function passed to the Foo constructor to be immediately executed. It's a function I'm holding onto so that it can be later invoked with Foo.STATIC_FIELD.bar(); What's the best way to achieve this?
My question was answered sufficiently in the comments by Mike C and DavidS. If you want to store a function for later invocation, don't use "new" because that will run the function. Later, be sure to call "call" on that function with the context of the object holding onto the function. For example:
foo.myFunction.call(foo);

Javascript Scope/Closure: Why can I access internal vars here?

I am currently working on a relatively simple project and discovered something:
var test = (function() {
var internal = 5;
return {
init: function() {
$(document).on('click', function() {
alert(internal);
});
}
};
}());
test.init();
I thought closure and javascript scope (as I understood it) meant that a function can only access its own variables, and those 1 level above it. So Why does this work? When I click on the document I get an alert of "5", I expected to get undefined.
Here is a JSFiddle showing what I'm doing:
http://jsfiddle.net/mcraig_brs/m644L/1/
I thought closure and javascript scope (as I understood it) meant that a function can only access its own variables, and those 1 level above it.
Nope, it's all levels above it. In fact, that's how global variables work in JavaScript; they're just an example of closures in action.
So Why does this work?
When the JavaScript engine needs to resolve a symbol, it looks first (loosely) in the execution context that the symbol appears in (in this case, the one created by the call to the anonymous function you're passing into on). If it doesn't find a matching variable there, it looks at the execution context that surrounds that one (in this case, the one created by calling init). If it doesn't find it there, it looks at the next one out (the one created by calling your outermost anonymous function). And if not there, the next level out, until it reaches the global execution context.
More about closures (on my blog): Closures are not complicated
Note that I kept saying "...created by the call to..." above. This is a critical point: There can be (almost always are) multiple execution contexts created for a given scope as a program runs. Consider:
function foo(name) {
return function() {
alert(name);
};
}
(This is only two levels again, but it applies to as many levels as you like.)
foo, when called, creates and returns a function that, when called, shows us the name that was passed into foo when that function was created:
var f1 = foo("one");
var f2 = foo("two");
f1(); // "one"
f2(); // "two"
Calling foo creates an execution context. The function foo creates has an enduring reference to the part of that context that contains variables for that call (the spec calls it the "variable binding object"). That binding object still exists after foo returns, which is why when we call the function foo creates, it still has access to the relevant name variable.
It's important to remember that it isn't that closures get a copy of the value of the variable. They get an enduring reference to that variable. Which is why this works:
function foo(a) {
return function() {
alert(++a);
};
}
var f = foo(0);
f(); // 1
f(); // 2
f(); // 3
Javascript is statically scoped. when you are writing a function, you will have access to all the variables available to you inside the function as they are available from where you are accessing it.
var a = 10;
function foo() {
// now i have access in a
var b = 20;
// i have access to both a and b
function bar() {
// still have access to both a and b
var c = 30;
// any more nested function will have access to a,b and c
}
}

Why does this refer to window or object based on where parenthesis are placed? And return undefined

I am working on flexible javascript widget. In the course of some testing, I noticed that the context of this changes based on whether the parenthesis used to call a function are placed inside an object or in the global context of its call. Why do the parenthesis matter? And why would parenthesis inside the object refer to window and when placed in global context refer to the object. It seems like it would be the other way around.
Also undefined is returned in both instances. Is there a way to execute the function without returning anything?
I feel like I'm missing something important about this and don't want to miss out.
//this refers to window
var dataSource = {
read: read()
};
function read(){
console.log(this);
}
dataSource.read;
//this refers to dataSource object
var dataSource = {
read: read
};
function read(){
console.log(this);
}
dataSource.read();
Your code is doing two different things.
The first example is executing read() as the object definition is executed (read() is available because it's a function declaration and is hoisted, though this isn't related to the problem you're experiencing). It is called without any context so its this is window (as per the specification, where window is the browser's global object).
The second example has a reference to read(), which is then executed at the end of the block. Because it's executed as a property of dataSource, its this will become that. However, if you first assigned that reference to somewhere else and then invoked it via that reference, you'd again lose that this context.
For fine-grained control of this, take a look at bind(), call() and apply().
Also undefined is returned in both instances. Is there a way to execute the function without returning anything?
A function always has a return value (undefined if not explicitly set), but you're free to ignore it.
The scoping of this can be a tricky topic in javascript. That said, I can expand my answer on the general rules regarding the scope of this if need be.
But to answer your specific question, whenever you reference this inside an object literal, it by default, refers to the object literal itself.
Edit: as long as the function was invoked as a property of the object literal.
Where as, almost in any other situation I can call to mind, this will refer to the window object unless specified when invoking said function using apply() or call().
When this is used outside of objects it refers to the global object which in browser environment is window. Otherwise it refers to the last bareword before the last dot in the invocation.
For example:
function foo () {return this};
var bin = {bar:{foo:foo},foo:foo};
foo(); // returns window
bin.foo(); // returns bin
bin.bar.foo(); // returns bar
// ^
// |
// '------ last bareword before the last dot in the invocation
Now, as to why the location of the parenthesis matter. I think you should be able to guess by now:
When we add a parenthesis to a word (variable/name/reference) what we're doing is make a function call:
foo(); // call foo
If we don't add the parenthesis, what we're doing is refer to the object:
foo; // this contains the function foo
Note that not adding the parens is not calling the function. Therefore it should be obvious that when you do:
var bar = { foofoo : foo() }
What you're doing is passing the result of the function foo to bar.foofoo. The function is invoked without any "dots" in its invocation path. Therefore it doesn't belong to any object and therefore the rule of this == window applies.
On the other hand if you do:
var bar = { foo : foo }
What you're doing is assign the function foo to bar.foo. When you later call it as:
bar.foo()
the invocation contains a "dot" therefore the rule about the last object before the last dot applies.
See my previous answer to a related question for a detailed explanation on how this works in javascript: How does the "this" keyword in Javascript act within an object literal?

why is this private method in a constructor?

I'm a bit puzzled by this coding pattern I've run into even though I've been studying up on 'this.' The following (simplified) code shows the pattern:
var MyConstructor = function MyConstructor() {
this._handlers = {
action: this.handleAction.bind(this)
};
};
MyConstructor.prototype.start = function(someObj) {
this.someObj.on(’some event’, this._handlers.action); //<--here
}
MyConstructor.prototype.handleAction = function() {
//do stuff
}
module.exports = MyConstructor;
My question is, why is the private method in the constructor required? Is this pattern avoid some common problem? Could the line commented //<--here simply be:
this.someObj.on(’some event’, this.handleAction);
No, they are different. The difference is in context, which means the value of this within the function.
this.handleAction passes the function to on without any context. There is no value of this specified. The value will be determined when the function is executed. It is very likely that the value will not be the a MyConstructor object, so this.start, for instance, will not refer to the right object, or indeed perhaps any object at all.
The solution is to bind context. This sets the context forever, so this will always refer to the right value. You see this line of code:
action: this.handleAction.bind(this)
This means that, when the code later refers to this._handlers.action, it will be sending the function to on with the appropriate context, so this will always point to the correct value.
The difference between the following lines
this.someObj.on(’some event’, this.handleAction.bind(this));
this.someObj.on(’some event’, this.handleAction);
... is that the first handleAction will run with this being the instance of MyConstructor, while the second will run in whatever context the event handling mechanism decides. If it is something like this, it will run with this being the global object:
function on (a, callback) {
callback(); // callback is run with this as the global object
// UNLESS it was bound to something else
}
The 'private' _handlers property is just an object that holds references to callbacks bound to the instance. If you were to call bind twice, two functions would be created. The _handlers property makes it so that a single bound function is created which can be used as a handler for any number of events.

JavaScript: How To `.bind()` `Function` to Another Object

The Facts
Function('return this')() always returns the global (window) object. Function.bind({})('return this')() returns the global object too.
My Goals
I want to create a variation of Function. The anonymous functions returned by calling that variation of Function should always use myObj as this.
If JavaScript wouldn't behave in that special way (see The Facts), I would do the following:
var myFun = Function.bind(myObj);
myFun is the object that I want to own. Now I would be able to do the following:
console.assert(myObj === myFun('return this')());
My Questions
Why is Function returning global, even after .bind()ing it to another object?
Is there a workaround? How can I bind Function to another object?
Thanks.
You are essentially doing this:
Function.call({}, 'return this;')();
The Function function is executed in the context of a new anonymous object. Doing this does not affect the context of the functions generated by Function. It turns out that Function doesn't care what context it runs in -- it always produces functions that have the default global context.
If you want to specify the context of the functions generated by Function, you want to wrap Function like this:
// give our vars privacy in a closure
(function() {
// store old Function
var oldFunc = Function;
// redefine Function to be a wrapper around the real Function
// which takes an additional `context` argument
Function = function(ftext, context) {
return oldFunc(ftext).bind(context);
}
}());
Now you can call Function('return this', myObj)(); and it will return myObj.
Or, to simply create your suggested myFun(text) syntax which passes your assert test:
var myFun = function(ftext) {
return Function(ftext).bind(myObj);
}
I don't know what exactly you are trying to achieve, but it seems that your method chaining is in the wrong order.
Function('return this').bind({})() // returns the empty Object

Categories

Resources