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

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

Related

Confused about when to use `bind` in an Event Handler

The following successfully prints 'foo'.
var obj = {
name: 'foo',
printName: function printName() {
console.log(this.name);
}
};
var printButton= document.getElementById('printIt');
printButton.addEventListener('click', function(){
obj.printName();
});
The following doesn't, however:
printButton.addEventListener('click', obj.printName() );
I know the solution... simply use bind so that we're referencing the obj object. i.e:
printButton.addEventListener('click', obj.printName.bind(obj) );
Why then don't we need to use bind in the first example. I don't know why wrapping obj.printName() function call in the anonymous function results in the console.log correctly referencing and printing this properly, but when called directly after click, you needs to use bind
Alright, I commented with some good information on this question so I might as well answer!
Functions are first class
Okay, let's starts with some fundamentals of javascript that is very dissimilar to some other programming languages: in javascript functions are first class citizens--which is just a fancy way of saying that you can save functions into variables and you can pass functions into other functions.
const myFunction = function () { return 'whoa a function'; }
array.map(function () { return x + 1; });
And because of this wonderful feature, there is a big difference between the expressions:
Expression 1
obj.printName
and
Expression 2
obj.printName();
In expression 1: the function isn't being invoked so the value of the expression is of type function
In expression 2: the function is being invoked so the value of the expression is what the function returns. In your case, that's undefined
addEventListener
The method addEventListener takes in two arguments:
a string of the type of event
a function that will be run when the event fires.
Alight, so what does that mean?
When you call
// doesn't work
printButton.addEventListener('click', obj.printName() );
you're not passing a value of type function to the addEventListener method, you're actually passing undefined.
// works
printButton.addEventListener('click', obj.printName.bind(obj) );
then works (for one reason) because the second argument is actually of type function.
What does bind do? Why does it return a function?
Now we need to discuss what bind actually does. It related to the pointer* this.
*by pointer, I mean a reference identifier to some object
bind is a method that exists on every function object that simply binds the this pointer of a desired object to the function
This is best shown by an example:
Say you have a class Fruit that has a method printName. Now that we know that you can save a method into a variable, let's try that. In the example below we're assigning two things:
boundMethod which used bind
unboundMethod that didn't use bind
class Fruit {
constructor() {
this.name = 'apple';
}
printName() {
console.log(this.name);
}
}
const myFruit = new Fruit();
// take the method `printName`
const boundMethod = myFruit.printName.bind(myFruit);
const unboundMethod = myFruit.printName;
boundMethod(); // works
unboundMethod(); // doesn't work
So what happens when you don't call bind? Why doesn't that work?
If you don't call bind in this case, the value of the function that gets stored into the identifier unboundMethod can be thought to be:
// doens't work
const unboundMethod = function() {
console.log(this.name);
}
where the contents of the function is the same contents of the method printName from the Fruit class. Do you see why this is an issue?
Because the this pointer is still there but the object it was intended to refer to is no longer in scope. When you try to invoke the unboundMethod, you'll get an error because it couldn't find name in this.
So what happens when you do use bind?
Loosely bind can be thought of as replacing the this value of function with the object you're passing into bind.
So if I assign: myFruit.printName.bind(myFruit) to boundMethod then you can think of the assignment like this:
// works
const boundMethod = function() {
console.log(myFruit.name);
}
where this is replaced with myFruit
The bottom-line/TL;DR
when to use bind in an Event Handler
You need to use Function.prototype.bind when you want to replace the thises inside the function with another object/pointer. If your function doesn't ever use this, then you don't need to use bind.
Why then don't we need to use bind in the first example?
If you don't need to "take the method" (i.e. taking the value of type of function), then you don't need to use bind either Another way to word that is: if you invoke the method directly from the object, you don't need bind that same object.
In the wrapper function, you're directly invoking the method of the object (as in expression 2). Because you're invoking the method without "taking the method" (we "took" the methods into variables in the Fruit example), you don't need to use bind.
printButton.addEventListener('click', function(){
// directly invoke the function
// no method "taking" here
obj.printName();
});
Hope this helps :D
Note: You need to call printButton.addEventListener('click', obj.printName() ); without parenthesis in obj.printName() since you want to pass the function.
The answer lies in the way this is bound in Javascript. In JS, the way a function is called decides how this is bound. So when you provide the callback function like below:
printButton.addEventListener('click', function(){
obj.printName();
});
Notice, printName is being called via dot notation. This is called implicit binding rule when this is bound to an object before dot, in this case obj. Clearly in this case, you get the expected output.
However, when you call it like this:
printButton.addEventListener('click', obj.printName );
Notice that, all you are passing is the address of the function that is inside obj. So in this case info about obj is lost. In other words, the code that calls back the function doesn't have the info about obj that could have been used to set this. All it has is the address of the function to call.
Hope this helps!
EDIT:
Look at this crude implementation I call bind2 that mimics native bind. This is just to illustrate how native bind function returns a new function.
Function.prototype.bind2 = function (context) {
var callBackFunction = this;//Store the function to call later
return function () { //return a new function
callBackFunction.call(context);//Later when called, apply
//context, this is `obj` passed
//in bind2()
}
};
function hello() {
alert(this.name);
}
obj = {
name:'ABC'
};
var f = hello.bind2(obj);
f();
Notice: How function f() is hard bound here. f() has hard bound this with obj. You cannot change this to other than obj now. This is another thing with bind that probably will help you knowing.

why does a variable need to be created in this closure

Hi I have the following closure
function createCounter() {
var numberOfCalls = 0;
return function() {
return ++numberOfCalls;
}
}
var fn = createCounter();
fn()
fn()
And I believe I understand about scope and the fact that the inner function keep the outer function's values after the outer one has returned.
What I don't understand is why I need to create this variable
var fn = createCounter()
and then invoke the variable fn() instead of initially invoking createCounter()
I saw that createCounter() just returns 'function()' instead of what has to be '1' and I don't understand why.
Thanks for the help. Read many tutorials still having problems with understanding this.
Please note: the question's isn't about how to make the code more eloquent or better, it's about understanding of what's been done
When createCounter is called it returns another function and that returned function is not evaluated unless you do so. Remember, in JavaScript functions are objects too. They can be the return value of a function.
So when you do this:
var fn = createCounter();
fn references only the function returned by createCounterfunction and not its evaluated value.
If you need to evaluate the function returned by createCounter try something like:
createCounter()();
This evaluates the returned function.
If you call it like this it will always return the same value as it creates a new numberOfCalls variable every time you call createCounter.
In Javascript, functions are objects which can be passed to and returned by other functions, as any other objects (e.g. a string, a number...).
So doing:
function foo(arg) { /* ... */ }
var someObject = new String("Hello");
foo(someObject);
is similar as:
function foo(arg) { /* ... */ }
var someFunction = new Function("Hello", "...");
foo(someFunction);
A function may thus return another function, which can be invoked as needed.
function foo() {
return new Function(...);
}
var functionReturnedByCallingFoo = foo();
functionReturnedByCallingFoo(); // can be invoked
functionReturnedByCallingFoo(); // and again
functionReturnedByCallingFoo(); // and again
Now, functions are almost never declared using the Function constructor, but rather with constructs named "function declarations" or "function expressions" - basically, the way we have defined the function "foo" in the previous examples, with a function signature and a function body delimited by curly brackets.
In such cases, the statements inside of the function body can read and write variables declared outside of the function itself ("free variables"), and not only variables declared within the function, as per the rules of lexical scoping. This is what we call a closure.
So in your case, the createCounter() function, when invoked, defines a local variable named "numberOfCalls", then return a function - the body of which having access to that variable. Executing the returned function changes the value of the variable, at each invocation, as it would for any "global" variable (i.e. variables declared in outer scopes).
Executing the createCounter() function many times would simply, each time, recreate a new local variable "numberOfCalls", initialize it to zero, and return a new function object having access to that variable.

Nested .bind not working as expected

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.

Defining a object's property based onanother object's property

I define an object called anotherObject with a function called anotherFunction based on the someFunction from the object someObject.
var someObject={
someFunction:function(){
return this;
}
};
console.log(someObject.someFunction()===someObject);//true
var someFunc=someObject.someFunction;
console.log(someFunc===someObject.someFunction);//true
//the function does not have the same context as that of the function called earlier...
console.log(someFunc()===someObject);//false
var anotherObject={
anotherFunction:someObject.someFunction
};
console.log(anotherObject.anotherFunction===someObject.someFunction);//true
console.log(anotherObject[anotherFunction]()===anotherObject);//true;
console.log(anotherObject.anotherFunction()===someObject);//false
Firefox Scratchpad reports that the function anotherFunction is not defined.
That's the way JavaScript functions actually work, the someFunction is a function which its responsibility is to return the this in the current context, no matter what is for this one:
var someFunc=someObject.someFunction;
you can call it using call or apply with whatever context you like:
var myobj = {};
console.log(someFunc.call(myobj)===myobj);//true
console.log(someFunc.apply(myobj)===myobj);//true
no matter what you pass as the first argument in call and apply, your function would return that very object. So as you see your function does what it is supposed to do, but if you want it to always return your first object someObject, you do not need to use this keyword.
Read my answer to the How does JavaScript .prototype work?, I have tried to dig into this concept in the first two parts.
And also this is one of the best resources you can find about this concepts:
Understanding JavaScript Function Invocation and “this”

how to use javascript functions? (defining functions in label)

There are different ways of defining the javascript functions. I often use the simplest way to define the function
function myfunc(){
}
and the next way to define the function in the variable like this (a little bit confusing the way of using)
var myvar = myfunc(){
/*some code*/
}
and the difficult way for me and mostly found in codes developed by advanced programmers like the following
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}
Please, can anyone clear my concept on this how can I use?
function myfunc(){}
Function declaration: the function is declared using the standard syntax
function functionName(params[]) {
//functionbody
}
Using this syntax declares the function at the begin of the scope execution, so they'll be available everywhere in their scope(and in their descendeant scopes).
var s = myfunc(); //s == 0
function myfunc() {return 0;}
var myfunc = function() {};
This uses the pattern known as function expression, it just assigns a reference of an anonymous function to a variable named myfunc. Using this syntax won't allow you to use the function until the variable is parsed. Even if variables are hoisted at the top of their scope, they're initialized when the interpreter parses them, so the above example won't work:
var s = myfunc(); //ReferenceError: myfunc is not defined
var myfunc = function() {return 0;};
But the example below will:
var myfunc = function() {return 0;};
var s = myfunc(); //s == 0
The third example is just assigning an anonymous function to an object property(also known as object method) in the way we've just done with function expression, so if I use the pattern above the code will become:
var onOpen = function() {},
onClose = function() {},
SqueezeBox = {//curly braces denotes an object literal
presets: {//again, this is a nested object literal
onOpen: onOpen,
onClose: onClose
}
};
This acts exactly the same as your example, with the only difference that here I used a variable to get a reference to the anonymous function before passing it to the object. If you need to know more about objects, I recommend you reading the MDN docs. Anyway, if you're really intrested in how JS works, I'd suggest Javascript Garden, which is a very good article about JS.
The first code snippet is a function declaration:
function myfunc() { }
You are declaring a named function called myfunc. You can verify this by myfunc.name === "myfunc"
Your second code snippet contains syntax error. I believe you meant:
var myvar = function() { };
This is an anonymous function expression assigned to a variable. You can verify this by typeof myvar === "function" and myvar.name === "".
The third snippet is a javascript object. Basically you can think of it as a Map or Dictionary<string, object>. So SqueezeBox contains 1 key presets, which in turn is a dictionary that contains 2 keys, onOpen and onClose, which both of them are anonymous functions.
In
var SqueezeBox={presets:{onOpen:function(){},onClose:function(){}}}
He's creating an object SqueezeBox containing another object presets with two empty anonymous functions, he's defining the function inline with an empty body inside the {}.
A better way to see it is formatted this way:
var SqueezeBox={
presets:{
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
There is a lot of useful information on this subject here
Functions can have a name, which if specified cannot be changed. Functions can also be assigned to variables like any other object in javascript.
The first example is of a function declaration:
function myfunc(){
}
Using the function declaration you will be able to call the function from anywhere within the closure in which the function is declared, even if it is declared after it is used.
The other two examples are function expressions:
var myvar = function(){
/*some code*/
}
var SqueezeBox= {
presets: {
onOpen:function(){/* empty function body */},
onClose:function(){/*empty function body */}
}
}
Using function expressions you are assigning functions to a variable. When doing this you must declare them before you use them. Most of the time you see this the functions will be anonymous but it is possible to name a function in an expression:
var myvar = function myFunc(){
myFunc(); // Because it has a name you can now call it recursively
}
When doing this, the myFunc function is only available within the body of the function because it is still a function expression rather than a declaration.
The third example declares a javascript object literal, SqueezeBox and within that object there is another called presets. Within this object there are two more objects/labels called onOpen and onClose. This means you can do the following to use these functions:
SqueezeBox.presets.onOpen();
SqueezeBox.presets.onClose();
You can think of onOpen and onClose as variables that are part of the object. So it's very similar to doing the following (but the variable is only in the scope of the presets object which is only available within the SqueezeBox object).
var onOpen = function() {};
This has already been answered here: What is the difference between a function expression vs declaration in Javascript?.
For the last example, as Atropo said, it's affecting an anonymous function to an object. It's similar to the var example.

Categories

Resources