apply和call的用法
1.每个函数都包含两个非继承而来的方法:call()方法和apply()方法.
2.这两个方法的作用都是一样的,在特定的作用域中调用函数,相当于设置函数体内this对象的值,以扩充函数赖以运行的作用域.
3.call和apply不同点,接收参数的方式不同,例:
function add(c,d){
return this.a + this.b + c + d;
}
var o = {a:1,b:2};
console.log(add.apply(o,[3,4])) // 1+2+3+4 = 10
console.log(add.call(o,5,6)) // 1+2+5+6 = 14
Array.prototype.slice.call(arguments)能将具有length属性的对象(key值为数字)转成数组
var obj = {0:'hello',1:'world',length:2};
console.log(Array.prototype.slice.call(obj,0));//["hello", "world"]
说明:apply和call接收的第一个参数都是能代表函数运行的作用域(this),不同之处是apply第二个参数接收的是函数的参数数组,而call需要吧函数的参数一个个列出来.
驼峰字符串和下划线字符串的转换
var a = 'liQingWu';
var b = 'li_qing_wu';
var c = a.replace(/([A-Z])/g,function (all) {
console.log(all);
return '_'+all.toLowerCase()
})
console.log(c);
var d = b.replace(/(_[a-z])/g,function (all) {
console.log(all);
return all.replace('_','').toUpperCase()
})
console.log(d);