Reputation: 1116
I have had a look at JavaScript's bind method and I'm not sure in which kind of situations I should be using it. Would the following example of getting a random card from a deck (array) of cards be considered an appropriate use of the method:
function getRandomElementFromArray () {
return this.splice( Math.floor( Math.random() * this.length ) )[0];
}
var deckOfCards = // Array of 52 cards;
var getRandomCard = getRandomElementFromArray.bind(deckOfCards);
Upvotes: 0
Views: 68
Reputation: 359
When you talk about "appropriate" you have to be a bit more specific. I think it is save to say, that your question can be answered by looking into some styleguides oder conventions. I have looked up one that explains it pretty much self speeking:
One of the deficiencies in Javascript is that callback functions are not bound to the correct or expected context (as referenced with the this variable). In ES2015, this problem is solved by using so-called arrow functions for callbacks.
However, while we're still writing ES5 code, we can use the .bind method to bind the correct this context to the callback method.
For example:
this.$el = $("#some-element");
setTimeout(function () {
// Without using .bind, "this" will refer to the window object.
this.$el.hide();
}.bind(this), 1000);
This is a styleguide written by Plone ( a content management system ) who may look at this problem from a perspective different then google or other companies. That's why you have to decide if it is "appropriate" in your context.
Link to the Styleguide: Plone Styleguide
Upvotes: 0
Reputation: 339786
I wouldn't say that's an appropriate use - the deck should be simply passed as a parameter.
The most common uses of .bind
are to specifically attach a given this
when it wouldn't otherwise be possible to pass it and/or to create a version of a function where the initial arguments are fixed and extra parameters passed are then added on, e.g.
For the former:
function MyObject() {
this.callback = function() { ... }
}
var myobj = new MyObject();
el.addEventListener("click", myobj.callback.bind(myobj));
[without the .bind
call the callback wouldn't refer to this
correctly]
For the latter:
function add(a, b) { return a + b }
var add2 = add.bind(null, 2); // no "this" needed in this case
add2(3); // returns 5
Upvotes: 1
Reputation: 7408
No. It should only be used in OOP when you have an object and you need to pass one method from its prototype
to another function. In other cases it generally just doesn't make sense.
function MyClass() {
this.name = 'foo';
}
MyClass.prototype.myMethod = function() { return this.name; }
var myObj = new MyClass();
// say we need to pass myObj.myMethod somewhere else
var func = myObj.myMethod;
func(); // undefined -- doesn't work.
var func2 = myObj.myMethod.bind(myObj);
func2(); // 'foo' -- works!
Upvotes: 0