仿JQuery输写高效JSLite代码的一些技巧

2020-05-23 06:01:12易采站长站整理

    $first.css(‘border’,’1px solid red’);
})
// 建议
$first.on(‘click’,function(){
    $first.css(‘border’,’1px solid red’);
    $first.css(‘color’,’blue’);
})

$first.on(‘hover’,function(){
    $first.css(‘border’,’1px solid red’);
})
精简javascript

一般来说,最好尽可能合并函数。

// 糟糕
$first.click(function(){
    $first.css(‘border’,’1px solid red’);
    $first.css(‘color’,’blue’);
});
// 建议
$first.on(‘click’,function(){
    $first.css({
        ‘border’:’1px solid red’,
        ‘color’:’blue’
    });
});
链式操作

JSLite实现方法的链式操作是非常容易的。下面利用这一点。

// 糟糕
$second.html(value);
$second.on(‘click’,function(){
    alert(‘hello everybody’);
});
$second.fadeIn(‘slow’);
$second.animate({height:’120px’},500);
// 建议
$second.html(value);
$second.on(‘click’,function(){
    alert(‘hello everybody’);
}).fadeIn(‘slow’).animate({height:’120px’},500);

维持代码的可读性

伴随着精简代码和使用链式的同时,可能带来代码的难以阅读。添加缩紧和换行能起到很好的效果。

// 糟糕
$second.html(value);
$second.on(‘click’,function(){
    alert(‘hello everybody’);
}).fadeIn(‘slow’).animate({height:’120px’},500);
// 建议
$second.html(value);
$second
    .on(‘click’,function(){ alert(‘hello everybody’);})
    .fadeIn(‘slow’)
    .animate({height:’120px’},500);
选择短路求值

短路求值是一个从左到右求值的表达式,用 &&(逻辑与)或 || (逻辑或)操作符。

// 糟糕
function initVar($myVar) {
    if(!$myVar) {
        $myVar = $(‘#selector’);
    }
}
// 建议
function initVar($myVar) {
    $myVar = $myVar || $(‘#selector’);
}
选择捷径

精简代码的其中一种方式是利用编码捷径。