【发布时间】:2014-01-14 21:11:49
【问题描述】:
我正在尝试深入了解并理解而不是重复代码。我知道bind, call and apply 通过修改this 指向的内容来更改执行上下文。我不明白的是,这些方法是必不可少的和/或导致代码更短的领域。考虑以下几点:
var person = {
firstName: 'john',
lastName: 'doe',
fullName: function () {
console.log(this.firstName + " " + this.lastName);
}
}
//#1, binder is an html button
$('#binder').click(person.fullName.bind(person)); //john doe
//#2, anonymous is an html button
$('#anonymous').click(function () {
person.fullName(); //john doe
});
//seems strange I see this application a lot 'borrowing' a method
//why?
var o = { firstName: 'obj', lastName: 'ect' };
person.fullName.call(o); //obj ect to console
我想知道一些关于何时使用 call 和 apply 是一种好的做法和/或节省大量时间的一般范例(并在不使用匿名函数 a la 函数 #1 之外进行绑定)
【问题讨论】:
-
apply 的另一个有用的方面是它允许您传递参数数组。在函数接受可变数量参数的情况下特别有用,例如jquery's
when -
这对代码的复用性来说基本是好的。
标签: javascript