##项目中js的那些tips
JS函数用法
1、replace()
背景:后端传来的姓名为类似“Taylor Alison Swift”这样带空格的字符串,甲方希望将个人账户密码初始为没有空格的姓名;
解决方案:replace();
replace()使用方法:
var employeeName = "Taylor Alison Swift"
//非贪婪匹配,只匹配第一个
document.write(employeeName.replace(/ /,"")) //输出:“TaylorAlison Swift”
//变量全局匹配
document.write(employeeName.replace(/ /g,"")) //输出“TaylorAlisonSwift”
//大小写不敏感,此外匹配模式方式可以像下例一样叠加
var str = "Taylor Taylor Alison Swift"
document.write(str.replace(/taylor/ig,"1")) //输出“1 1 Alison Swift”
2、this指针的使用
2.1 call()和apply()
目的:改变函数体this指针的指向,当另一个对象想使用某个对象中的方法时,可以不需要再重新写一份,直接去“劫持”this指针即可。
call()和apply()的使用方法:
function popQueen(){}
popQueen.prototype = {
album: "RED",
say: function(){
console.log("Taylor's most valuable album is " + this.color);
}
};
var another = {
album: "REPUTATION"
};
var folk = new popQueen;
folk.say(); //Taylor's most valuable album is RED
folk.say.call(another); //Taylor's most valuable album is REPUTATION
folk.say.apply(another); //Taylor's most valuable album is REPUTATION
//coding differences
call(thisObj, arg1, arg2, arg3, arg4);
apply(thisObj, [args]);
2.2 bind()强制扭转this指针指向
var foo = {
x: 3
}
var bar = function(){
console.log(this.x);
}
bar();
// undefined
var boundFunc = bar.bind(foo);
boundFunc();
// 3