使用hasOwnProperty监测对象是否含有某个属性

1、示例代码

<!DOCTYPE html>
<html lang="zh">

    <head>
        <meta charset="UTF-8" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <meta http-equiv="X-UA-Compatible" content="ie=edge" />
        <title>hasOwnProperty使用</title>

    </head>

    <body>

        <script type="text/javascript">
            let dict = {
                name: 'mfg'
            }
            console.log(dict.hasOwnProperty('name'));
            let dictNew = {
                name: 'mfg',
                hasOwnProperty: 10
            }
            //报错 dictNew.hasOwnProperty is not a function
            //因为dictNew 修改了hasOwnProperty的实现
            //console.log(dictNew.hasOwnProperty('name'));
            let hasOwn = Object.prototype.hasOwnProperty;
            console.log(hasOwn.call(dictNew, 'name'))
        </script>
    </body>

</html>

2、说明

(1) 在使用hasOwnProperty方法时,最好使用Object.prototype.hasOwnProperty.call方式(推荐!!),以防止对象对hasOwnProperty方法重新实现。

(2) 写法:

Object.prototype.hasOwnProperty === [].hasOwnProperty

原文地址:https://www.cnblogs.com/mengfangui/p/9841823.html