zoukankan      html  css  js  c++  java
  • 使用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

  • 相关阅读:
    按回车键提交表单
    Access数据库类型及属性
    Problem 1002
    问题 1003
    Problem 1003
    Switch Game(摘自LP学C++)
    1006
    膜拜蛇形矩阵
    A == B?
    Rectangles
  • 原文地址:https://www.cnblogs.com/mengfangui/p/9841823.html
Copyright © 2011-2022 走看看