前端项目js部分的tips

##项目中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
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值