1、属性设置,不定长变量
/**
* Set attribute `name` to `val`, or get attr `name`.
*
* @param {Element} el
* @param {String} name
* @param {String} [val]
* @api public
*/
function attr(el, name, val) {
// get
if (arguments.length == 2) {
return el.getAttribute(name);
}
// remove
if (val === null) {
return el.removeAttribute(name);
}
// set
el.setAttribute(name, val);
return el;
}
2、debounce
/**
* Debounce fn, calling it only once if
* the given time elapsed between calls.
*
* @param {Function} fn
* @param {Number} timeout
*
* @return {Function} debounced function
*/
function debounce(fn, timeout) {
var timer;
var lastArgs;
var lastThis;
var lastNow;
function fire() {
var now = Date.now();
var scheduledDiff = lastNow + timeout - now;
if (scheduledDiff > 0) {
return schedule(scheduledDiff);
}
fn.apply(lastThis, lastArgs);
timer = lastNow = lastArgs = lastThis = undefined;
}
function schedule(timeout) {
timer = setTimeout(fire, timeout);
}
return function () {
lastNow = Date.now();
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
lastArgs = args;
lastThis = this; // ensure an execution is scheduled
if (!timer) {
schedule(timeout);
}
};
}
3、使用 apply、call、bind
使用 apply、call、bind 函数也是可以改变 this 的指向的,原理稍后再讲,我们先来看一下是怎么实现的:
使用 apply
使用 call
使用 bind
刚刚我们已经介绍了 apply、call、bind 都是可以改变 this 的指向的,但是这三个函数稍有不同。
apply() 方法调用一个函数, 其具有一个指定的this值,以及作为一个数组(或类似数组的对象)提供的参数
fun.apply(thisArg, [argsArray])
- thisArg:在 fun 函数运行时指定的 this 值。需要注意的是,指定的 this 值并不一定是该函数执行时真正的 this 值,如果这个函数处于非严格模式下,则指定为 null 或 undefined 时会自动指向全局对象(浏览器中就是window对象),同时值为原始值(数字,字符串,布尔值)的 this 会指向该原始值的自动包装对象。
- argsArray:一个数组或者类数组对象,其中的数组元素将作为单独的参数传给 fun 函数。如果该参数的值为null 或 undefined,则表示不需要传入任何参数。从ECMAScript 5 开始可以使用类数组对象。浏览器兼容性请参阅本文底部内容。
apply 和 call 的区别
其实 apply 和 call 基本类似,他们的区别只是传入的参数不同。
所以 apply 和 call 的区别是 call 方法接受的是若干个参数列表,而 apply 接收的是一个包含多个参数的数组。
bind 和 apply、call 区别
bind()方法创建一个新的函数, 当被调用时,将其this关键字设置为提供的值,在调用新函数时,在任何提供之前提供一个给定的参数序列。