compulsive binding of this with functions
I was just going through the code of jBox.js and came across the following lines of code:
jQuery(document).on('keyup.jBox-' + this.id, function(ev) {
(ev.keyCode == 37) && this.showImage('prev');
(ev.keyCode == 39) && this.showImage('next');
}.bind(this));
Have a look at the code HERE , this guy seems to compulsively bind functions with the value of this
, I have a few questions regarding this pattern.
Is this some kind of design pattern ?
What is the author trying to achieve by binding most methoding with this
?
For instance take the above snippet of code, what is the author trying to achieve by binding the function with this
. (My guess is bind is functioning similar to jQuerys $.proxy here ? maintaining the value of this inside a new function definition.).
In the code you showed, if you removed the .bind(this)
call, then this
within the keyup.jBox-
handler would be set to whichever DOM node triggered the event. The author, though, apparently wants this
to be equal to whatever this
is (probably the jBox
instance?) at the point where the handler itself is created.
I don't know if I would consider this a "design pattern", it's just a language feature that allows the author to enforce that this
is exactly what they want it to be, regardless of how the function itself is invoked.
My guess is bind is functioning similar to jQuerys $.proxy here?
Yes, it's very similar.
Quick example:
function Person(name) {
this.name = name;
this.greet = function() {
console.log('Hello, my name is ' + this.name);
};
};
var tenali = new Person('Tenali');
tenali.greet();
// > Hello, my name is Tenali
Great, this works, because I, as the author, expect you to always access this as <person-instance>.greet()
. What happens if someone breaks that assumption, though:
var jeremy = new Person('Jeremy');
var greet = jeremy.greet;
greet();
// > Hello, my name is undefined
Obviously not working as intended, because now greet()
is being invoked as a plain ol' function, completely detached from jeremy
as the context target (which is normally inferred in JavaScript by the .
notation used to invoke a method).
Now, as a consumer of the Person
instance, you can still force this
to be jeremy
again by using .call()
or .apply()
:
var jeremy = new Person('Jeremy');
var greet = jeremy.greet;
greet.apply(jeremy);
// > Hello, my name is Jeremy
...which is nice, but not exactly elegant. So, to make things easier on you, I could have instead forced this
to be what I wanted it to be, as follows:
function Person(name) {
this.name = name;
this.greet = function() {
console.log('Hello, my name is ' + this.name);
}.bind(this);
};
Now, if we go back to the earlier example, we'll see that it works as intended, as I've "bound" the greet()
function to the Person instance already:
var jeremy = new Person('Jeremy');
var greet = jeremy.greet;
greet();
// > Hello, my name is Jeremy
链接地址: http://www.djcxy.com/p/2880.html
上一篇: 检查字符串是否符合要求
下一篇: 这与功能的强制性绑定