解剖JS原型对象,让世界没有混淆的对象😂

前言:记录对对象属性的再次学习,对象属性很多概念性都比较容易让人混淆(至少我是经常的混淆... 大笑ing - )

1. hasOwnProperty和in属性

hasOwnProperty的作用:检查对象中是否存在指定的实例属性,重点是实例而非原型属性。hasOwnProperty个人直译:拥有自己的属性...方便好记😝

语法:对象.hasOwnProperty(“属性名”)

代码示例

<script>

    //01 提供一个构造函数
    function User(name) {
        this.name = name;
    }

    //02 设置构造函数的原型对象的属性
    User.prototype.todo = function () {
        console.log("to do some...");
    }

    User.prototype.des = "默认的描述信息";

    //03 创建对象
    var user = new User();

    //04 使用hasOwnProperty方法判断该属性是否是对象的实例属性
    console.log(user.hasOwnProperty("age"));       //false
    console.log(user.hasOwnProperty("name"));      //true
    console.log(user.hasOwnProperty("todo"));  //false
    console.log(user.hasOwnProperty("des"));       //false

</script>

in关键字作用:用来检查对象中是否存在某个属性(不区分实例属性和原型属性)...😌如果是用在for循环上的in就不是这个意思了

语法:“属性名” in 对象

代码示例

<script>

    //01 提供一个构造函数
    function User(name) {
        this.name = name;
    }

    //02 设置构造函数的原型对象的属性
    User.prototype.todo = function () {
        console.log("to do some...");
    }

    //03 创建对象
    var user = new User();

    //04 使用in关键字判断对象中是否存在以下属性:name age todo
    console.log("age" in user);       //false
    console.log("name" in user);      //true
    console.log("todo" in user);  //true

</script>

那么我们如何判断对象中只存在原型属性呢?

function isProperty(obj, property) {
   return !obj.hasOwnProperty(property) && (property in obj); 
}

  • 如果想知道user是属于某个构造函数时直接user.constructor查看

  • 如果想要判断user这个对象是不是User构造函数的实例时用instanceof检查

 console.log(user instanceof User);      //true
 console.log(user instanceof Object);      //true
 //instanceof 直接查到整条原型链
  • 如果还要判断User是不是user的原型对象时,可以用isPrototypeOf
console.log(User.prototype.isPrototypeOf(user));    //rue


总结:会很容易懵逼... 前方的道路还是很多雾霾...且行且懵逼...

---查看原文--来自漂亮妹纸写的文章

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容