对象-判断属性是否存在的方法补充

对象的方法补充

◼ hasOwnProperty
  对象是否有某一个属于自己的属性(不是在原型上的属性)
◼ in/for in 操作符
  判断某个属性是否在某个对象或者对象的原型上
◼ instanceof
  用于检测构造函数(PersonStudent类)的pototype,是否出现在某个实例对象的原型链上
◼ isPrototypeOf
  用于检测某个对象,是否出现在某个实例对象的原型链上
案例:

    <script src="./js/inherit_untils.js"></script>
    <script>
      var obj = {
        name:"hdc",
        age:21
      }
      var info = createObject(obj)
      info.address = "中国"
      info.intro = "中国大好河山"

      console.log(info.name,info.address)
      console.log(info)

      // 1. hasOwnProperty 判断属性是否在自己的上面不再原型上面
      console.log(info.hasOwnProperty("name"))//false
      console.log(info.hasOwnProperty("address"))//true

      // 2. in 操作符 判断某个属性是否在某个对象或者对象的原型上
      console.log("name" in info)//true
      console.log("address" in info) // true
      //注意:for in 遍历不仅仅是遍历自己对象上的内容,也包括原型上的内容
      for (var key in info){
        console.log(key)
      }

      // 3. instanceof 用于检测构造函数(Person、Student类)的pototype,是否出现在某个实例对象的原型链上(实例对象和类的关系)
      function Person(){}
      function Student(){}
      inherit(Student,Person)
      //实例对象
      var stu = new Student()

      console.log(stu instanceof Student) //true
      console.log(stu instanceof Person) // true
      console.log(stu instanceof Object) // true
      console.log(stu instanceof Array) // false

      // 4. isPrototypeOf 用于检测某个对象,是否出现在某个实例对象的原型链上(实例对象和实例对象的关系)
      console.log(Student.prototype.isPrototypeOf(stu)) // true
      console.log(Person.prototype.isPrototypeOf(stu)) // true
      // 可以判断对象之间的继承
      console.log(obj.isPrototypeOf(info))
    </script>
posted @   韩德才  阅读(7)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
点击右上角即可分享
微信分享提示