return false 和 return true

常规用法

在普通函数中:return 语句终止函数的执行,并返回一个指定的值给函数调用者,一般会用一个变量接收这个返回值再进行其它处理。如果未指定返回值,则返回 undefined
其中,返回一个函数是一个很重要的使用方式,可参看闭包的使用

在Generator中:return 语句可在生成器中使用,表现和普通函数基本一致。
也可以通过gen.return(value)使用,不管生成器是否结束,调用该方法均会返回给定的value并结束生成器。如果未指定value也会返回undefined

值得注意的:

  1. 如果一个函数没有return关键字时,返回给函数调用者的仍是undefined;
  2. return只能终止函数且只能终止当前函数的执行,不会影响其外部函数;
  3. 数组遍历方法如map,foreach,filter,reduce中的回调函数中 return 的作用有各自的说明,无普通函数的表现。

特殊用法

1. 阻止默认事件(十分不推荐)

目前return false在jQuery中可同时阻止冒泡和默认事件。但是在原生JS中只能阻止默认事件,并且也只能在HTML事件属性和DOM0级事件处理方法中才能通过返回 return false的形式阻止,因此建议采用标准方法去阻止默认事件。
阻止默认事件示例:

    //html
    <a href="https://www.baidu.com" id="btn">跳转不</a>
    
    //js
    var btn = document.getElementById("btn");
    btn.onclick = function(e) {
        console.log("点击了,但是!");
        //return false; //可以阻止,但不建议使用
        window.event? window.event.returnValue = false : e.preventDefault();//推荐使用
    }
    btn.addEventListener("click",function(e){
        console.log("点击了,但是!");
        return false;//这种方式是阻止不了默认事件的,因为不是DOM0级事件
        // window.event? window.event.returnValue = false : e.preventDefault();//推荐使用
    })

另外:

    //html
    <a href="https://www.baidu.com" id="btn" onclick="handle()">跳转不</a>
    //js
    function handle(){
        return false;
    }

上面这种写法是阻止不了默认事件的,因为阻止默认事件的正确姿势是onclick="return false",而上面这种写法相当于onclick="false"

阻止冒泡示例

    //html
    <div id="father" class="father">
        这是父级
        <div id="child" class="child">
            这是子级
            <p>冒泡不</p>
        </div>
    </div>

    //js
    var father = document.getElementById("father");
    var child = document.getElementById("child");
    father.onclick = function() {
        console.log("点击了父级");
    };
    child.onclick = function(e) {
        console.log("点击了子级");
        //return false;  //无用
        window.event ? window.event.cancelBubble = true : e.stopPropagation();//可以阻止冒泡
    }

    //css
    .father {
        background: yellow;
        padding: 10px;
    }

    .child {
        background: red;
    }

2. 在window.onerror中的使用

return false虽然被许多事件赋予了阻止默认事件的能力,但是onerror却是个例外!

详细说明可参看:window.onerrorDefault actions and cancelable events

    //可以阻止异常信息在控制台中显示,线上可以自行收集异常信息后阻止外人看到控制台报错,开发环境不建议使用。
    window.onerror = function(msg, url, line, col, error) {
        console.log("------errorInfo---",msg, url, line, col, error)
        return true;   //这里用return false不行!
    }
    window.addEventListener('error', (function(e) {
        console.log("-----errorEvent----", e)
        e.preventDefault()  //这里换成 return false或return true均不行
    }), true);
posted @ 2017-06-05 11:58  冰凌哒雪花  阅读(1070)  评论(0编辑  收藏  举报