Methods(Object's function) can refer to object's variable using the "this" keyword.
Can function's properties refer to function variables?
Eg:-
function foo()
{
var x=5;
}
foo.help = {o1:x};// o1 is not initialized to x.
//Using o1:this.x also doesn't help. Why? Explain please.
Is there anyway to initialize o1 to x?
Example 9-1. A simple JavaScript class
// range.js: A class representing a range of values.
// This is a factory function that returns a new range object.
function range(from, to) {
// Use the inherit() function to create an object that inherits from the
// prototype object defined below. The prototype object is stored as
// a property of this function, and defines the shared methods (behavior)
// for all range objects.
var r = inherit(range.methods);
// Store the start and end points (state) of this new range object.
// These are noninherited properties that are unique to this object.
r.from = from;
r.to = to;
// Finally return the new object
return r;
}
// This prototype object defines methods inherited by all range objects.
range.methods = {
// Return true if x is in the range, false otherwise
// This method works for textual and Date ranges as well as numeric.
includes: function(x) { return this.from <= x && x <= this.to; },
// Invoke f once for each integer in the range.
// This method works only for numeric ranges.
foreach: function(f) {
for(var x = Math.ceil(this.from); x <= this.to; x++) f(x);
},
// Return a string representation of the range
toString: function() { return "(" + this.from + "..." + this.to + ")"; }
};
// Here are example uses of a range object.
var r = range(1,3); // Create a range object
r.includes(2); // => true: 2 is in the range
r.foreach(console.log); // Prints 1 2 3
console.log(r); // Prints (1...3)
What I understand :
Range is a function with variable from and to.
Range.methods is Range's property.It is defined outside Range() but it can still access from and to (using this.from and this.to ). How?
Thank you.
EDIT
this answer is based on edited question -- original answer is below
Your understanding is a little backwards.
The function doesn't have from and to in the way you think it does.
If I built this a different way, to get almost all of the same functionality, but be much, much easier for a person who is new to JS to understand, I would write it like this:
// my `makeRange` function makes an object
// then it gives it all of the things a range object needs
// then it returns the new object
var makeRange = function (min, max) {
// there are cleaner more-compact ways of doing this
// I'm writing this out in long-form to show you exactly what's going on
var rangeObject = {};
rangeObject.from = min;
rangeObject.to = max;
rangeObject.includes = includes;
rangeObject.foreach = foreach;
rangeObject.toString = toString;
return rangeObject;
};
// these are all of the functions inside of `range.methods`
// they don't have to be attached to the function ***AT ALL***, for ***ANY REASON***
// other than the author wanted them to be there for the sake of organization
// Here, I'm just putting them out on their own, for sake of clarity
var includes = function (x) { return this.from <= x && x <= this.to; },
foreach = function (func) {
var min = this.from,
max = this.to,
i = 0;
for (i = min; i <= max; i += 1) { func(i); }
},
toString = function () { return "(" + this.from + "..." + this.to + ")"; };
var range_3_to_5 = makeRange(3, 5),
range_6_to_12 = makeRange(6, 12);
range_3_to_5.from; // 3
range_6_to_12.includes(8); // true
range_6_to_12.foreach(function (i) { console.log(i); }); // [logs:] 6,7,8,9,10,11,12
The methods on range in the example aren't a part of the function.
They're methods which are given to the objects, as they are constructed.
In the example you gave, this is happening inside of the r = inherit(range.methods); call, which isn't explained in that block of code.
The this doesn't refer to the function at all.
It refers to the final object which uses the methods, at the time the method is called.
My range_3_to_5 and range_6_to_12 are both using the same copy of includes.
When range_3_to_5.includes(6); is called, this is set to range_3_to_5, and then the function uses this.from and this.to to determine if x is in the range.
There's no complex magic here.
We're just calling a function which "makes" something in a specific way, like a factory assembly-line, and then passes the finished version out.
It's attaching shared functions to each copy on the assembly line, and those shared functions use this to figure out which copy they're dealing with at the time.
var car = { license : "a32 vx98" },
truck = { license : "vdx 2000" },
jeep = { license : "mkv 3a2b" };
var read_license = function () { console.log(this.license); };
car.read_license = read_license;
truck.read_license = read_license;
car.read_license(); // [logs:] a32 vx98
truck.read_license(); // [logs:] vdx 2000
I can even call the function on its own, using the function's .call or .apply method to manually set this.
read_license.call(jeep); // [logs:] mkv 3a2b
Or use .bind to save a version of the function which ALWAYS uses the same value for this.
var read_car_license = read_license.bind(car);
read_car_license(); // a32 vx98
previous answer below
Not even remotely.
Variables live inside of the functions that they're created in:
var myFunction = function () {
var myValue = 23;
console.log(myValue);
};
myFunction(); // [log:] 23
console.log(myValue); // undefined
Values can live inside of functions further in:
var myFunction = function () {
var myValue = 23,
sayValue = function () {
console.log(myValue);
};
sayValue(); // will log 23 when you call `myFunction`
}
myFunction(); // [log:] 23
But if you want your variable to live OUTSIDE of the function (instead of further inside), then you either need to return the value to something, or set it to something, directly, from inside of the function.
var myOutsideValue = 42,
myFunction = function () {
var myValue = 23;
myOutsideValue = myValue;
};
console.log(myOutsideValue); // 42
myFunction();
console.log(myOutsideValue); // 23
Or returned...
var myReturnedValue = 0,
myFunction = function () {
var myValue = 23;
return myValue;
};
myReturnedValue = myFunction();
console.log(myReturnedValue); // [log:] 23
Or you can pass in an array or object to modify:
var myObject = {},
myFunction = function (obj) {
var myValue = 23;
obj.value = myValue;
};
myFunction(myObject);
console.log(myObject.value); // [log:] 23
Functions CAN reference themselves.
And because in JavaScript, functions are objects (and can have their own properties and methods), you can add things to them the same way you'd add properties to any {} object.
var myFunc = function () {
var myValue = 23;
myFunc.properties = {};
myFunc.properties.value = myValue;
};
myFunc();
console.log(myFunc.properties.value); // [logs:] 23
None of this has anything to do with this.
this is used for the opposite of what you're looking for.
It's for when you're inside a function which is attached to an object, and you want to read other properties/run other methods that are on that object.
var myObject = {
x : 23,
y : 42,
sayX : function () { console.log(this.x); },
sayY : function () { console.log(this.y); }
};
myObject.sayX(); // [logs:] 23
this is used in a couple of other spots, but really, that's it's primary role: accessing or setting values/methods on the object which the function is attached to (either through dot-property access obj.func(), or through manual setting, using .call/.apply/.bind), with the other very regular situation being the creation of new objects, using the new keyword.
So the way to get your x to work isn't to figure out this, it's to set it within the function, itself, or, more-appropriately, pass x out (return x) to another variable, outside, and then set the value yourself.
var foo = function () {
var x = "x";
return x;
},
variable; // === undefined
foo.help = { o1 : 0 };
variable = foo(); // variable === "x"
foo.help.o1 = variable;
// or shorter: foo.help.o1 = foo();
Alternative:
var help = { o1 : 0 },
foo = function (obj) {
var x = "x";
obj.o1 = x;
};
foo(help);
foo.help = help;
this only works inside of functions
var obj = {};
obj.x = 12;
obj.y = this.x + 5; // DOESN'T WORK
If this works in the last example, it's only because it's using this from inside of a function which would be referring to the FUNCTION'S this, and not to obj. And if you're calling a function which isn't attached to an object (obj.func(); or func.call(obj) or new_func = func.bind(obj);), then this will point to window.
In the context foo.help = {o1: x}, you are not in the same lexical scope as the definition of x, which would be inside of the foo function scope. This also applies to this.x (which apply in object scope).
function foo() {
var x = 5;
this.help = x;
}
Related
I have a function which has other functions defined:
var A = function(n) {
console.log(n + A.num());
}
A.num = function() {
return 5;
}
I want to change the name to B and delete A:
var B = A;
A = undefined;
But, when I do B(), It gives an error throws: "Cannot read property 'num' of undefined", which is completely normal and expected.
How do I handle this?
PS: Anyone who thinks that changing A.num() with this.num(), It will not work
You can always refer to the current function using its explicit name (if it has one).
So, change the definition, to name the function, and refer to it using that:
var A = function currentFunction(n) {
console.log(n + currentFunction.num());
}
A.num = function() {
return 5;
}
var B = A;
A = undefined;
B(10); //15
console.log(typeof currentFunction) //undefined, function name is local
Note: the abovementioned approach won't work if the function is named implicitly, but will continue to work if the function is renamed via fn.name
Alternatively, if the function isn't an arrow function, you can also use arguments.callee, that will work even with anonymous functions, but its use isn't recommended:
var A = function (n) {
console.log(n + arguments.callee.num());
}
A.num = function() {
return 5;
}
var B = A;
A = undefined;
B(10); //15
Unfortunately, none of the above will work with arrow functions, if you want to refer to itself, use a named bound function expression instead.
actually that's normal, because in js you can't really copy object
// Define object bar
var bar = {
x : 'Hi'
}
console.log(bar.x); //Hi
// Assign it to foo
var foo = bar;
console.log(foo.x); //Hi
//But
foo.x = 'Hello!! Im foo.';
console.log(foo.x); //Hello!! Im foo.
console.log(bar.x); //Hello!! Im foo.
bar.x = "Nice to meet you foo!!";
console.log(foo.x); //Nice to meet you foo!!
console.log(bar.x); //Nice to meet you foo!!
you have to return a new one with the same value as the last
var foo = {...bar};
and this is not working because B is always calling 'num' from A that doesn't exist, One way to sever the parity would be stringify the initial function, then use a function constructor to create the clone after replacing the 'A' by 'B'
but tell me more why are you facing this problem ?
var A = function(n) {
if(!this.num){
console.log("This is not available coz obj is not created");
console.log("Below error is for testing purpose");
}
let a=this.num(n);
console.log(a);
}
//use prototype here
//A.num = function() {
A.prototype.num=function(n){
return n+5;
}
//use new to create object
new A(5);
var B = A;
A = undefined;
//use new to create object
new B(6);
B(5);//lets try without using new keyword
.as-console-wrapper { max-height: 100% !important; top: 0; }
What is the use of bind() in JavaScript?
Bind creates a new function that will force the this inside the function to be the parameter passed to bind().
Here's an example that shows how to use bind to pass a member method around that has the correct this:
var myButton = {
content: 'OK',
click() {
console.log(this.content + ' clicked');
}
};
myButton.click();
var looseClick = myButton.click;
looseClick(); // not bound, 'this' is not myButton - it is the globalThis
var boundClick = myButton.click.bind(myButton);
boundClick(); // bound, 'this' is myButton
Which prints out:
OK clicked
undefined clicked
OK clicked
You can also add extra parameters after the 1st (this) parameter and bind will pass in those values to the original function. Any additional parameters you later pass to the bound function will be passed in after the bound parameters:
// Example showing binding some parameters
var sum = function(a, b) {
return a + b;
};
var add5 = sum.bind(null, 5);
console.log(add5(10));
Which prints out:
15
Check out JavaScript Function bind for more info and interactive examples.
Update: ECMAScript 2015 adds support for => functions. => functions are more compact and do not change the this pointer from their defining scope, so you may not need to use bind() as often. For example, if you wanted a function on Button from the first example to hook up the click callback to a DOM event, the following are all valid ways of doing that:
var myButton = {
... // As above
hookEvent(element) {
// Use bind() to ensure 'this' is the 'this' inside click()
element.addEventListener('click', this.click.bind(this));
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// Use a new variable for 'this' since 'this' inside the function
// will not be the 'this' inside hookEvent()
var me = this;
element.addEventListener('click', function() { me.click() });
}
};
Or:
var myButton = {
... // As above
hookEvent(element) {
// => functions do not change 'this', so you can use it directly
element.addEventListener('click', () => this.click());
}
};
The simplest use of bind() is to make a function that, no matter
how it is called, is called with a particular this value.
x = 9;
var module = {
x: 81,
getX: function () {
return this.x;
}
};
module.getX(); // 81
var getX = module.getX;
getX(); // 9, because in this case, "this" refers to the global object
// create a new function with 'this' bound to module
var boundGetX = getX.bind(module);
boundGetX(); // 81
Please refer to this link on MDN Web Docs for more information:
Function.prototype.bind()
bind allows-
set the value of "this" to an specific object. This becomes very helpful as sometimes this is not what is intended.
reuse methods
curry a function
For example, you have a function to deduct monthly club fees
function getMonthlyFee(fee){
var remaining = this.total - fee;
this.total = remaining;
return this.name +' remaining balance:'+remaining;
}
Now you want to reuse this function for a different club member. Note that the monthly fee will vary from member to member.
Let's imagine Rachel has a balance of 500, and a monthly membership fee of 90.
var rachel = {name:'Rachel Green', total:500};
Now, create a function that can be used again and again to deduct the fee from her account every month
//bind
var getRachelFee = getMonthlyFee.bind(rachel, 90);
//deduct
getRachelFee();//Rachel Green remaining balance:410
getRachelFee();//Rachel Green remaining balance:320
Now, the same getMonthlyFee function could be used for another member with a different membership fee. For Example, Ross Geller has a 250 balance and a monthly fee of 25
var ross = {name:'Ross Geller', total:250};
//bind
var getRossFee = getMonthlyFee.bind(ross, 25);
//deduct
getRossFee(); //Ross Geller remaining balance:225
getRossFee(); //Ross Geller remaining balance:200
From the MDN docs on Function.prototype.bind() :
The bind() method creates a new function that, when called, has its
this keyword set to the provided value, with a given sequence of
arguments preceding any provided when the new function is called.
So, what does that mean?!
Well, let's take a function that looks like this :
var logProp = function(prop) {
console.log(this[prop]);
};
Now, let's take an object that looks like this :
var Obj = {
x : 5,
y : 10
};
We can bind our function to our object like this :
Obj.log = logProp.bind(Obj);
Now, we can run Obj.log anywhere in our code :
Obj.log('x'); // Output : 5
Obj.log('y'); // Output : 10
This works, because we bound the value of this to our object Obj.
Where it really gets interesting, is when you not only bind a value for this, but also for its argument prop :
Obj.logX = logProp.bind(Obj, 'x');
Obj.logY = logProp.bind(Obj, 'y');
We can now do this :
Obj.logX(); // Output : 5
Obj.logY(); // Output : 10
Unlike with Obj.log, we do not have to pass x or y, because we passed those values when we did our binding.
Variables has local and global scopes. Let's suppose that we have two variables with the same name. One is globally defined and the other is defined inside a function closure and we want to get the variable value which is inside the function closure. In that case we use this bind() method. Please see the simple example below:
var x = 9; // this refers to global "window" object here in the browser
var person = {
x: 81,
getX: function() {
return this.x;
}
};
var y = person.getX; // It will return 9, because it will call global value of x(var x=9).
var x2 = y.bind(person); // It will return 81, because it will call local value of x, which is defined in the object called person(x=81).
document.getElementById("demo1").innerHTML = y();
document.getElementById("demo2").innerHTML = x2();
<p id="demo1">0</p>
<p id="demo2">0</p>
Summary:
The bind() method takes an object as an first argument and creates a new function. When the function is invoked the value of this in the function body will be the object which was passed in as an argument in the bind() function.
How does this work in JS anyway
The value of this in javascript is dependent always depends on what Object the function is called. The value of this always refers to the object left of the dot from where is the function is called. In case of the global scope this is window (or global in nodeJS). Only call, apply and bind can alter the this binding differently. Here is an example to show how the this keyword works:
let obj = {
prop1: 1,
func: function () { console.log(this); }
}
obj.func(); // obj left of the dot so this refers to obj
const customFunc = obj.func; // we store the function in the customFunc obj
customFunc(); // now the object left of the dot is window,
// customFunc() is shorthand for window.customFunc()
// Therefore window will be logged
How is bind used?
Bind can help in overcoming difficulties with the this keyword by having a fixed object where this will refer to. For example:
var name = 'globalName';
const obj = {
name: 'myName',
sayName: function () { console.log(this.name);}
}
const say = obj.sayName; // we are merely storing the function the value of this isn't magically transferred
say(); // now because this function is executed in global scope this will refer to the global var
const boundSay = obj.sayName.bind(obj); // now the value of this is bound to the obj object
boundSay(); // Now this will refer to the name in the obj object: 'myName'
Once the function is bound to a particular this value we can pass it around and even put it on properties on other objects. The value of this will remain the same.
The bind() method creates a new function instance whose this value is bound to the value that was passed into bind().
For example:
window.color = "red";
var o = { color: "blue" };
function sayColor(){
alert(this.color);
}
var objectSayColor = sayColor.bind(o);
objectSayColor(); //blue
Here, a new function called objectSayColor() is created from sayColor() by calling bind() and passing in the object o. The objectSayColor() function has a this value equivalent to o, so calling the function, even as a global call, results in the string “blue” being displayed.
Reference : Nicholas C. Zakas - PROFESSIONAL JAVASCRIPT® FOR WEB DEVELOPERS
I will explain bind theoretically as well as practically
bind in javascript is a method -- Function.prototype.bind . bind is a method. It is called on function prototype. This method creates a function whose body is similar to the function on which it is called but the 'this' refers to the first parameter passed to the bind method. Its syntax is
var bindedFunc = Func.bind(thisObj,optionsArg1,optionalArg2,optionalArg3,...);
Example:--
var checkRange = function(value){
if(typeof value !== "number"){
return false;
}
else {
return value >= this.minimum && value <= this.maximum;
}
}
var range = {minimum:10,maximum:20};
var boundedFunc = checkRange.bind(range); //bounded Function. this refers to range
var result = boundedFunc(15); //passing value
console.log(result) // will give true;
Creating a new Function by Binding Arguments to Values
The bind method creates a new function from another function with one or more arguments bound to specific values, including the implicit this argument.
Partial Application
This is an example of partial application. Normally we supply a function with all of its arguments which yields a value. This is known as function application. We are applying the function to its arguments.
A Higher Order Function (HOF)
Partial application is an example of a higher order function (HOF) because it yields a new function with a fewer number of argument.
Binding Multiple Arguments
You can use bind to transform functions with multiple arguments into new functions.
function multiply(x, y) {
return x * y;
}
let multiplyBy10 = multiply.bind(null, 10);
console.log(multiplyBy10(5));
Converting from Instance Method to Static Function
In the most common use case, when called with one argument the bind method will create a new function that has the this value bound to a specific value. In effect this transforms an instance method to a static method.
function Multiplier(factor) {
this.factor = factor;
}
Multiplier.prototype.multiply = function(x) {
return this.factor * x;
}
function ApplyFunction(func, value) {
return func(value);
}
var mul = new Multiplier(5);
// Produces garbage (NaN) because multiplying "undefined" by 10
console.log(ApplyFunction(mul.multiply, 10));
// Produces expected result: 50
console.log(ApplyFunction(mul.multiply.bind(mul), 10));
Implementing a Stateful CallBack
The following example shows how using binding of this can enable an object method to act as a callback that can easily update the state of an object.
function ButtonPressedLogger()
{
this.count = 0;
this.onPressed = function() {
this.count++;
console.log("pressed a button " + this.count + " times");
}
for (let d of document.getElementsByTagName("button"))
d.onclick = this.onPressed.bind(this);
}
new ButtonPressedLogger();
<button>press me</button>
<button>no press me</button>
As mentioned, Function.bind() lets you specify the context that the function will execute in (that is, it lets you pass in what object the this keyword will resolve to in the body of the function.
A couple of analogous toolkit API methods that perform a similar service:
jQuery.proxy()
Dojo.hitch()
Bind Method
A bind implementation might look something like so:
Function.prototype.bind = function () {
const self = this;
const args = [...arguments];
const context = args.shift();
return function () {
return self.apply(context, args.concat([...arguments]));
};
};
The bind function can take any number of arguments and return a new function.
The new function will call the original function using the JS Function.prototype.apply method.The apply method will use the first argument passed to the target function as its context (this), and the second array argument of the apply method will be a combination of the rest of the arguments from the target function, concat with the arguments used to call the return function (in that order).
An example can look something like so:
function Fruit(emoji) {
this.emoji = emoji;
}
Fruit.prototype.show = function () {
console.log(this.emoji);
};
const apple = new Fruit('🍎');
const orange = new Fruit('🍊');
apple.show(); // 🍎
orange.show(); // 🍊
const fruit1 = apple.show;
const fruit2 = apple.show.bind();
const fruit3 = apple.show.bind(apple);
const fruit4 = apple.show.bind(orange);
fruit1(); // undefined
fruit2(); // undefined
fruit3(); // 🍎
fruit4(); // 🍊
/**
* Bind is a method inherited from Function.prototype same like call and apply
* It basically helps to bind a function to an object's context during initialisation
*
* */
window.myname = "Jineesh";
var foo = function(){
return this.myname;
};
//IE < 8 has issues with this, supported in ecmascript 5
var obj = {
myname : "John",
fn:foo.bind(window)// binds to window object
};
console.log( obj.fn() ); // Returns Jineesh
Consider the Simple Program listed below,
//we create object user
let User = { name: 'Justin' };
//a Hello Function is created to Alert the object User
function Hello() {
alert(this.name);
}
//since there the value of this is lost we need to bind user to use this keyword
let user = Hello.bind(User);
user();
//we create an instance to refer the this keyword (this.name);
Simple Explanation:
bind() create a new function, a new reference at a function it returns to you.
In parameter after this keyword, you pass in the parameter you want to preconfigure. Actually it does not execute immediately, just prepares for execution.
You can preconfigure as many parameters as you want.
Simple Example to understand bind:
function calculate(operation) {
if (operation === 'ADD') {
alert('The Operation is Addition');
} else if (operation === 'SUBTRACT') {
alert('The Operation is Subtraction');
}
}
addBtn.addEventListener('click', calculate.bind(this, 'ADD'));
subtractBtn.addEventListener('click', calculate.bind(this, 'SUBTRACT'));
The bind function creates a new function with the same function body as the function it is calling .It is called with the this argument .why we use bind fun. : when every time a new instance is created and we have to use first initial instance then we use bind fun.We can't override the bind fun.simply it stores the initial object of the class.
setInterval(this.animate_to.bind(this), 1000/this.difference);
function.prototype.bind() accepts an Object.
It binds the calling function to the passed Object and the returns
the same.
When an object is bound to a function, it means you will be able to
access the values of that object from within the function using
'this' keyword.
It can also be said as,
function.prototype.bind() is used to provide/change the context of a
function.
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<= this.power; i++) {
product*=number;
}
return product;
}
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
let powerOfThree = powerOfNumber.bind({power:3});
alert(powerOfThree(2));
let powerOfFour = powerOfNumber.bind({power:4});
alert(powerOfFour(2));
Let us try to understand this.
let powerOfNumber = function(number) {
let product = 1;
for (let i = 1; i <= this.power; i++) {
product *= number;
}
return product;
}
Here, in this function, this corresponds to the object bound to the function powerOfNumber. Currently we don't have any function that is bound to this function.
Let us create a function powerOfTwo which will find the second power of a number using the above function.
let powerOfTwo = powerOfNumber.bind({power:2});
alert(powerOfTwo(2));
Here the object {power : 2} is passed to powerOfNumber function using bind.
The bind function binds this object to the powerOfNumber() and returns the below function to powerOfTwo. Now, powerOfTwo looks like,
let powerOfNumber = function(number) {
let product = 1;
for(let i=1; i<=2; i++) {
product*=number;
}
return product;
}
Hence, powerOfTwo will find the second power.
Feel free to check this out.
bind() function in Javascript
The bind() method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.
An example for the first part
grabbed from react package useSt8
import { useState } from "react"
function st8() {
switch(arguments.length) {
case 0: return this[0]
case 1: return void this[1](arguments[0])
default: throw new Error("Expected 0 or 1 arguments")
}
}
function useSt8(initial) {
// this in st8 will be something like [state, setSatate]
return st8.bind(useState(initial))
}
// usage
function Counter() {
const count = useSt8(0);
return (
<>
Count: {count()}
<button onClick={() => count(0)}>Reset</button>
<button onClick={() => count(prevCount => prevCount + 1)}>inc</button>
</>
);
}
An example for the second part
const add = (a, b) => a+b
someThis = this
// new function with this value equal to someThis
add5 = add.bind(someThis, 5)
add5(10) // 15
// we don't use this in add decelartion so this will work too.
add10 = add.bind(null, 10)
add10(5) // 15
Here's the simplest possible explanation:
Say you have a function
function _loop(n) { console.log("so: " + n) }
obviously you can call it like _loop(69) as usual.
Rewrite like this:
var _loop = function() { console.log("so: " + this.n) }
Notice there are now
no arguments as such
you use "this. " to get to the named arguments
You can now call the function like this:
_loop.bind( {"n": 420} )
That's it.
Most typical use case:
A really typical use is when you need to add an argument to a callback.
Callbacks can't have arguments.
So just "rewrite" the callback as above.
Simple example
function lol(second, third) {
console.log(this.first, second, third);
}
lol(); // undefined, undefined, undefined
lol('1'); // undefined, "1", undefined
lol('1', '2'); // undefined, "1", "2"
lol.call({first: '1'}); // "1", undefined, undefined
lol.call({first: '1'}, '2'); // "1", "2", undefined
lol.call({first: '1'}, '2', '3'); // "1", "2", "3"
lol.apply({first: '1'}); // "1", undefined, undefined
lol.apply({first: '1'}, ['2', '3']); // "1", "2", "3"
const newLol = lol.bind({first: '1'});
newLol(); // "1", undefined, undefined
newLol('2'); // "1", "2", undefined
newLol('2', '3'); // "1", "2", "3"
const newOmg = lol.bind({first: '1'}, '2');
newOmg(); // "1", "2", undefined
newOmg('3'); // "1", "2", "3"
const newWtf = lol.bind({first: '1'}, '2', '3');
newWtf(); // "1", "2", "3"
Another usage is that you can pass binded function as an argument to another function which is operating under another execution context.
var name = "sample";
function sample(){
console.log(this.name);
}
var cb = sample.bind(this);
function somefunction(cb){
//other code
cb();
}
somefunction.call({}, cb);
In addition to what have been said, the bind() method allows an object to borrow a method from another object without making a copy of that method. This is known as function borrowing in JavaScript.
i did not read above code but i learn something in simple so want to share here about bind method after bind method we can use it as any normal method.
<pre> note: do not use arrow function it will show error undefined </pre>
let solarSystem = {
sun: 'red',
moon : 'white',
sunmoon : function(){
let dayNight = this.sun + ' is the sun color and present in day and '+this.moon + ' is the moon color and prenet in night';
return dayNight;
}
}
let work = function(work,sleep){
console.log(this.sunmoon()); // accessing the solatSystem it show error undefine sunmmon untill now because we can't access directly for that we use .bind()
console.log('i work in '+ work +' and sleep in '+sleep);
}
let outPut = work.bind(solarSystem);
outPut('day','night')
bind is a function which is available in java script prototype, as the name suggest bind is used to bind your function call to the context whichever you are dealing with for eg:
var rateOfInterest='4%';
var axisBank=
{
rateOfInterest:'10%',
getRateOfInterest:function()
{
return this.rateOfInterest;
}
}
axisBank.getRateOfInterest() //'10%'
let knowAxisBankInterest=axisBank.getRateOfInterest // when you want to assign the function call to a varaible we use this syntax
knowAxisBankInterest(); // you will get output as '4%' here by default the function is called wrt global context
let knowExactAxisBankInterest=knowAxisBankInterest.bind(axisBank); //so here we need bind function call to its local context
knowExactAxisBankInterest() // '10%'
How do I pass variables by reference in JavaScript?
I have three variables that I want to perform several operations to, so I want to put them in a for loop and perform the operations to each one.
Pseudocode:
myArray = new Array(var1, var2, var3);
for (var x = 0; x < myArray.length; x++){
// Do stuff to the array
makePretty(myArray[x]);
}
// Now do stuff to the updated variables
What is the best way to do this?
There is no "pass by reference" available in JavaScript. You can pass an object (which is to say, you can pass-by-value a reference to an object) and then have a function modify the object contents:
function alterObject(obj) {
obj.foo = "goodbye";
}
var myObj = { foo: "hello world" };
alterObject(myObj);
alert(myObj.foo); // "goodbye" instead of "hello world"
You can iterate over the properties of an array with a numeric index and modify each cell of the array, if you want.
var arr = [1, 2, 3];
for (var i = 0; i < arr.length; i++) {
arr[i] = arr[i] + 1;
}
It's important to note that "pass-by-reference" is a very specific term. It does not mean simply that it's possible to pass a reference to a modifiable object. Instead, it means that it's possible to pass a simple variable in such a way as to allow a function to modify that value in the calling context. So:
function swap(a, b) {
var tmp = a;
a = b;
b = tmp; //assign tmp to b
}
var x = 1, y = 2;
swap(x, y);
alert("x is " + x + ", y is " + y); // "x is 1, y is 2"
In a language like C++, it's possible to do that because that language does (sort-of) have pass-by-reference.
edit — this recently (March 2015) blew up on Reddit again over a blog post similar to mine mentioned below, though in this case about Java. It occurred to me while reading the back-and-forth in the Reddit comments that a big part of the confusion stems from the unfortunate collision involving the word "reference". The terminology "pass by reference" and "pass by value" predates the concept of having "objects" to work with in programming languages. It's really not about objects at all; it's about function parameters, and specifically how function parameters are "connected" (or not) to the calling environment. In particular, note that in a true pass-by-reference language — one that does involve objects — one would still have the ability to modify object contents, and it would look pretty much exactly like it does in JavaScript. However, one would also be able to modify the object reference in the calling environment, and that's the key thing that you can't do in JavaScript. A pass-by-reference language would pass not the reference itself, but a reference to the reference.
edit — here is a blog post on the topic. (Note the comment to that post that explains that C++ doesn't really have pass-by-reference. That is true. What C++ does have, however, is the ability to create references to plain variables, either explicitly at the point of function invocation to create a pointer, or implicitly when calling functions whose argument type signature calls for that to be done. Those are the key things JavaScript doesn't support.)
Primitive type variables like strings and numbers are always passed by value.
Arrays and Objects are passed by reference or by value based on these conditions:
if you are setting the value of an object or array it is Pass by Value.
object1 = { prop: "car" };
array1 = [1,2,3];
if you are changing a property value of an object or array then it is Pass by Reference.
object1.prop = "car";
array1[0] = 9;
Code
function passVar(obj1, obj2, num) {
obj1.prop = "laptop"; // will CHANGE original
obj2 = { prop: "computer" }; //will NOT affect original
num = num + 1; // will NOT affect original
}
var object1 = {
prop: "car"
};
var object2 = {
prop: "bike"
};
var number1 = 10;
passVar(object1, object2, number1);
console.log(object1); // output: Object { prop: "laptop" }
console.log(object2); // output: Object { prop: "bike" }
console.log(number1); // ouput: 10
Workaround to pass variable like by reference:
var a = 1;
inc = function(variableName) {
window[variableName] += 1;
};
inc('a');
alert(a); // 2
And yup, actually you can do it without access a global variable:
inc = (function () {
var variableName = 0;
var init = function () {
variableName += 1;
alert(variableName);
}
return init;
})();
inc();
Simple Object
function foo(x) {
// Function with other context
// Modify `x` property, increasing the value
x.value++;
}
// Initialize `ref` as object
var ref = {
// The `value` is inside `ref` variable object
// The initial value is `1`
value: 1
};
// Call function with object value
foo(ref);
// Call function with object value again
foo(ref);
console.log(ref.value); // Prints "3"
Custom Object
Object rvar
/**
* Aux function to create by-references variables
*/
function rvar(name, value, context) {
// If `this` is a `rvar` instance
if (this instanceof rvar) {
// Inside `rvar` context...
// Internal object value
this.value = value;
// Object `name` property
Object.defineProperty(this, 'name', { value: name });
// Object `hasValue` property
Object.defineProperty(this, 'hasValue', {
get: function () {
// If the internal object value is not `undefined`
return this.value !== undefined;
}
});
// Copy value constructor for type-check
if ((value !== undefined) && (value !== null)) {
this.constructor = value.constructor;
}
// To String method
this.toString = function () {
// Convert the internal value to string
return this.value + '';
};
} else {
// Outside `rvar` context...
// Initialice `rvar` object
if (!rvar.refs) {
rvar.refs = {};
}
// Initialize context if it is not defined
if (!context) {
context = this;
}
// Store variable
rvar.refs[name] = new rvar(name, value, context);
// Define variable at context
Object.defineProperty(context, name, {
// Getter
get: function () { return rvar.refs[name]; },
// Setter
set: function (v) { rvar.refs[name].value = v; },
// Can be overrided?
configurable: true
});
// Return object reference
return context[name];
}
}
// Variable Declaration
// Declare `test_ref` variable
rvar('test_ref_1');
// Assign value `5`
test_ref_1 = 5;
// Or
test_ref_1.value = 5;
// Or declare and initialize with `5`:
rvar('test_ref_2', 5);
// ------------------------------
// Test Code
// Test Function
function Fn1(v) { v.value = 100; }
// Test
function test(fn) { console.log(fn.toString()); console.info(fn()); }
// Declare
rvar('test_ref_number');
// First assign
test_ref_number = 5;
test(() => test_ref_number.value === 5);
// Call function with reference
Fn1(test_ref_number);
test(() => test_ref_number.value === 100);
// Increase value
test_ref_number++;
test(() => test_ref_number.value === 101);
// Update value
test_ref_number = test_ref_number - 10;
test(() => test_ref_number.value === 91);
Yet another approach to pass any (local, primitive) variables by reference is by wrapping variable with closure "on the fly" by eval. This also works with "use strict". (Note: be aware that eval is not friendly to JavaScript optimizers, and also missing quotes around variable name may cause unpredictive results)
"use strict"
// Return text that will reference variable by name (by capturing that variable to closure)
function byRef(varName){
return "({get value(){return "+varName+";}, set value(v){"+varName+"=v;}})";
}
// Demo
// Assign argument by reference
function modifyArgument(argRef, multiplier){
argRef.value = argRef.value * multiplier;
}
(function(){
var x = 10;
alert("x before: " + x);
modifyArgument(eval(byRef("x")), 42);
alert("x after: " + x);
})()
Live sample: https://jsfiddle.net/t3k4403w/
There's actually a pretty sollution:
function updateArray(context, targetName, callback) {
context[targetName] = context[targetName].map(callback);
}
var myArray = ['a', 'b', 'c'];
updateArray(this, 'myArray', item => {return '_' + item});
console.log(myArray); //(3) ["_a", "_b", "_c"]
I personally dislike the "pass by reference" functionality offered by various programming languages. Perhaps that's because I am just discovering the concepts of functional programming, but I always get goosebumps when I see functions that cause side effects (like manipulating parameters passed by reference). I personally strongly embrace the "single responsibility" principle.
IMHO, a function should return just one result/value using the return keyword. Instead of modifying a parameter/argument, I would just return the modified parameter/argument value and leave any desired reassignments up to the calling code.
But sometimes (hopefully very rarely), it is necessary to return two or more result values from the same function. In that case, I would opt to include all those resulting values in a single structure or object. Again, processing any reassignments should be up to the calling code.
Example:
Suppose passing parameters would be supported by using a special keyword like 'ref' in the argument list. My code might look something like this:
//The Function
function doSomething(ref value) {
value = "Bar";
}
//The Calling Code
var value = "Foo";
doSomething(value);
console.log(value); //Bar
Instead, I would actually prefer to do something like this:
//The Function
function doSomething(value) {
value = "Bar";
return value;
}
//The Calling Code:
var value = "Foo";
value = doSomething(value); //Reassignment
console.log(value); //Bar
When I would need to write a function that returns multiple values, I would not use parameters passed by reference either. So I would avoid code like this:
//The Function
function doSomething(ref value) {
value = "Bar";
//Do other work
var otherValue = "Something else";
return otherValue;
}
//The Calling Code
var value = "Foo";
var otherValue = doSomething(value);
console.log(value); //Bar
console.log(otherValue); //Something else
Instead, I would actually prefer to return both new values inside an object, like this:
//The Function
function doSomething(value) {
value = "Bar";
//Do more work
var otherValue = "Something else";
return {
value: value,
otherValue: otherValue
};
}
//The Calling Code:
var value = "Foo";
var result = doSomething(value);
value = result.value; //Reassignment
console.log(value); //Bar
console.log(result.otherValue);
These code examples are quite simplified, but it roughly demonstrates how I personally would handle such stuff. It helps me to keep various responsibilities in the correct place.
Happy coding. :)
I've been playing around with syntax to do this sort of thing, but it requires some helpers that are a little unusual. It starts with not using 'var' at all, but a simple 'DECLARE' helper that creates a local variable and defines a scope for it via an anonymous callback. By controlling how variables are declared, we can choose to wrap them into objects so that they can always be passed by reference, essentially. This is similar to one of the Eduardo Cuomo's answer above, but the solution below does not require using strings as variable identifiers. Here's some minimal code to show the concept.
function Wrapper(val){
this.VAL = val;
}
Wrapper.prototype.toString = function(){
return this.VAL.toString();
}
function DECLARE(val, callback){
var valWrapped = new Wrapper(val);
callback(valWrapped);
}
function INC(ref){
if(ref && ref.hasOwnProperty('VAL')){
ref.VAL++;
}
else{
ref++;//or maybe throw here instead?
}
return ref;
}
DECLARE(5, function(five){ //consider this line the same as 'let five = 5'
console.log("five is now " + five);
INC(five); // increment
console.log("five is incremented to " + five);
});
Actually it is really easy. The problem is understanding that once passing classic arguments, you are scoped into another, read-only zone.
The solution is to pass the arguments using JavaScript's object-oriented design. It is the same as putting the arguments in a global/scoped variable, but better...
function action(){
/* Process this.arg, modification allowed */
}
action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();
You can also promise stuff up to enjoy the well-known chain:
Here is the whole thing, with promise-like structure
function action(){
/* Process this.arg, modification allowed */
this.arg = ["a", "b"];
}
action.setArg = function(){this.arg = arguments; return this;}
action.setArg(["empty-array"], "some string", 0x100, "last argument")()
Or better yet...
action.setArg(["empty-array"],"some string",0x100,"last argument").call()
JavaScript can modify array items inside a function (it is passed as a reference to the object/array).
function makeAllPretty(items) {
for (var x = 0; x < myArray.length; x++){
// Do stuff to the array
items[x] = makePretty(items[x]);
}
}
myArray = new Array(var1, var2, var3);
makeAllPretty(myArray);
Here's another example:
function inc(items) {
for (let i=0; i < items.length; i++) {
items[i]++;
}
}
let values = [1,2,3];
inc(values);
console.log(values);
// Prints [2,3,4]
Putting aside the pass-by-reference discussion, those still looking for a solution to the stated question could use:
const myArray = new Array(var1, var2, var3);
myArray.forEach(var => var = makePretty(var));
As we don't have javascript pass by reference functionality, the only way to do this is to make the function return the value and let the caller assign it:
So
"makePretty(myArray[x]);"
should be
"myArray[x] = makePretty(myArray[x]);"
This is in case you need assignment inside the function, if only mutation is necessary, then passing the object and mutating it should be enough
I know exactly what you mean. The same thing in Swift will be no problem. The bottom line is use let, not var.
The fact that primitives are passed by value, but the fact that the value of var i at the point of iteration is not copied into the anonymous function is quite surprising to say the least.
for (let i = 0; i < boxArray.length; i++) {
boxArray[i].onclick = function() { console.log(i) }; // Correctly prints the index
}
If you want to pass variables by reference, a better way to do that is by passing your arguments in an object and then start changing the value by using window:
window["varName"] = value;
Example:
// Variables with first values
var x = 1, b = 0, f = 15;
function asByReference (
argumentHasVars = {}, // Passing variables in object
newValues = []) // Pass new values in array
{
let VarsNames = [];
// Getting variables names one by one
for(let name in argumentHasVars)
VarsNames.push(name);
// Accessing variables by using window one by one
for(let i = 0; i < VarsNames.length; i += 1)
window[VarsNames[i]] = newValues[i]; // Set new value
}
console.log(x, b, f); // Output with first values
asByReference({x, b, f}, [5, 5, 5]); // Passing as by reference
console.log(x, b, f); // Output after changing values
I like to solve the lack of by reference in JavaScript like this example shows.
The essence of this is that you don't try to create a by reference. You instead use the return functionality and make it able to return multiple values. So there isn't any need to insert your values in arrays or objects.
var x = "First";
var y = "Second";
var z = "Third";
log('Before call:',x,y,z);
with (myFunc(x, y, z)) {x = a; y = b; z = c;} // <-- Way to call it
log('After call :',x,y,z);
function myFunc(a, b, c) {
a = "Changed first parameter";
b = "Changed second parameter";
c = "Changed third parameter";
return {a:a, b:b, c:c}; // <-- Return multiple values
}
function log(txt,p1,p2,p3) {
document.getElementById('msg').innerHTML += txt + '<br>' + p1 + '<br>' + p2 + '<br>' + p3 + '<br><br>'
}
<div id='msg'></div>
Using Destructuring here is an example where I have 3 variables, and on each I do the multiple operations:
If value is less than 0 then change to 0,
If greater than 255 then change to 1,
Otherwise dived the number by 255 to convert from a range of 0-255 to a range of 0-1.
let a = 52.4, b = -25.1, c = 534.5;
[a, b, c] = [a, b, c].map(n => n < 0 ? 0 : n > 255 ? 1 : n / 255);
console.log(a, b, c); // 0.20549019607843136 0 1
I have two JavaScript objects.
Obj1 - static class
Obj2 - instance
After adding item in Obj1 and running the method isAdded() from Obj2 there is a problem.
obj1.func stores a function, that holds the keyword this for Obj2. If I call Obj1.func([args]) this is now for Obj1 instead of Obj2.
Any answer Please?
var Obj1=function(){};
Obj1.func=null;
Obj1.addItem=function(vstup){
// code for add - AJAX async ....
// after adding
Obj1.func(id, nazev);
};
// ----------------------------
var Obj2=function(){
this.variable=null;
this.promenna2=null;
this.isAdded=function(){
this.variable="added";
alert("ok");
};
};
// ---------------------
// in body
window.onload=function(){
var instanceObj2=new Obj2();
obj1.func=instanceObj2.isAdded();
obj1.addItem("test");
}
You are doing obj1.func = instanceObj2.isAdded() which means: setobj1.functo the result ofinstanceObj2.isAdded(), which is: obj1.func = undefined since obj2.isAdded() returns nothing.
if you then execute obj1.isAdded(), which runs Obj1.func, you are essentially executing undefined as a function.
To fix it:
obj1.func = function() { instanceObj2.isAdded(); };
Calling something within another context (aka: running something and setting "this")
To run something with a different this value:
To set the context of a function, you can use either apply or call
function add()
{
var result = this;
for(var i = 0, l = arguments.length; i < l; i++)
result += arguments[i];
return result;
}
var value = 2;
newValue = add.apply(value, [3,4,5]); // = 2 + 3 + 4 + 5;
// newValue = 5
newValue = add.call(value, 3, 4, 5) // same as add.apply, except apply takes an array.
Creating a new function, with a context
In new browsers (ie9+) it's possible to use Function.prototype.bind to create a callback with a set context (this) and set arguments which precede other arguments.
callback = func.bind(object);
callback = function() { func.apply(object, arguments); }
callback = func.bind(object, 1, 2);
callback = function() { func.apply(object, [1, 2]); };
In javascript this refers to currently being used element, So it's reference keep changing
Best method is to store (this) in a variable. and use it where you want that.
Like
var obj1This=this;
var obj2This=this;
And later use them
obj2This.isAdded();
I understand the general idea behind the this keyword but I'm having trouble figuring out what it actually refers to in practice. For example, in both these example exercises, I guessed the wrong number.
for question1, I said that the alert would be '5', because it is referring to the this.x outside the anonymous function in the function.
In question2, I thought the alert would be 5 because this line
var alertX = o.alertX;
would bind the value 5 for property x inside the variable o to the new variable 'alertX' which becomes the function call in the next line: alertX();
Can you explain why I'm wrong?
var question1 = function() {
this.x = 5;
(function() {
var x = 3;
this.x = x;
})();
alert(this.x);
};
var answer1 = 3;
var question2 = function() {
this.x = 9;
var o = {
'x':5,
'alertX':function() { alert(this.x); }
};
var alertX = o.alertX;
alertX();
}
var answer2 = 9;
In the first case, when you invoke a method with no explicit receiver this is the Global object (the window in a web browser).
Similarly in the second case: even though the function is defined on the object, and you are inside another, by invoking the function with alertx() the this is set to the Global/window.
In short:
For foo.bar(), the this inside of bar will be foo.
For bar(), the this will be the Global object.
This includes so-called "self-invoking lambdas", i.e. (function(){ ... })().
For bar.call(whee) and bar.apply(whee), the this will be whee (because that's what these methods do).
Another example:
var o1 = { name:"o1", f:function(){ console.log(this.name) } };
var o2 = { name:"o2" };
o2.gogogo = o1.f;
o2.gogogo(); // Will output "o2"
These are good examples of how interesting this becomes in Javascript. this always refers to the context in which it was invoked / called, not simply where it is at that moment! question2 is a perfect example of it.
I'm assuming you are invoking these globally like so:
question1();
question2();
In question1:
You have an anonymous function that is ran after you first set x to 5. This anonymous function if not set to a variable, inside a function etc, would have this set to the global variable of window. But you have it within a function & set to variable question1. So when it runs itself, it sets this's (which is question1 function) x variable to 3.
In question2:
X is originally set to 9, this being question2 in this instance. Now the part that is throwing you off is that, even though within the o {} object you set x : 5. And your alertX function is calling this.x. All of this would lead you to think it will alert 5! But you are invoking your alert function outside of the o {} object, hence the this refers to question2 function again!
Put the following into your browser's console
var x = -1, log = function(){ // set up some stuff
if(console) if(console.log) return console.log.apply(console, arguments),undefined;
return alert(arguments.join(', ')),undefined;
},
question1 = function() {
this.x = 5; // question1.x is 5
(function() { // anonymous function fires in global 'window'
var x = 3; // so window.x is now 3
this.x = x; // this is window
})();
log('ans1',this.x,this); // see below
},
question2 = function() {
this.x = 9; // question2.x is 9
var o = {
'x':5, // o.x is 5
'alertX':function() { log('ans2',this.x,this); }
};
var alertX = o.alertX; // alertX === o.alertX
alertX(); // being called in global scope
// to make alertX have scope of question2
this.alertX = o.alertX; // this is question2
this.alertX(); // so we're calling from question2
},
a1 = new question1(), // note the new operator
a2 = new question2();
undefined;
And you'll get
ans1 5 question1
ans2 3 Window
ans2 9 question2