JS 关键字 instanceof 和 isPrototypeOf 及判断属性

instanceof

  • instanceof用于判断 "对象" 是否是指定构造函数的 "实例"
           class Person{
                constructor(myName) {
                    this.name = myName;
                }
            }
            let p = new Person();
            console.log(p instanceof Person); // true

            class Cat{
                name = "mm";
            }
            let mm = new Cat();
            console.log(mm instanceof Person); // false

  • instanceof 注意点
    只要 构造函数的原型对象出现在实例对象的原型链中都会返回true
           function Person(myName) {
                this.name = myName;
            }

            function Student(myName, myScore){
                Person.call(this,myName);
                this.score = myScore;
            }

            Student.prototype = new Person();
            Student.prototype.constructor = Student;

            let stu = new Student();

            console.log(stu instanceof Person); // true

isPrototypeOf用于判断 一个对象是否是另一个对象的原型

           class Person{
                name = "henry";
            }
            let p = new Person();
            console.log(Person.prototype.isPrototypeOf(p));  // true

            class Cat{
                name = "mm";
            }
            console.log(Cat.prototype.isPrototypeOf(p)); //  false

isPrototypeOf 的注意点

  • 只要调用者在传入对象的原型链上都会返回true
            function Person(myName) {
                this.name = myName;
            }

            function Student(myName,myScore) {
                Person.call(this,myName);
                this.score = myScore;
            }

            Student.prototype = new Person();
            Student.prototype.constructor = Student;

            let stu = new Student();

            console.log(Person.prototype.isPrototypeOf(stu)); // true

判断属性

  1. 判断某一个对象是否拥有某一个属性
  • in的特点: 只要类中或者原型对象中有, 就会返回true
            class Font{
                length = 45;
            }
            Font.prototype.height = 60;

            let f = new Font();

            console.log("length" in f); // true
            console.log("width" in f); // false
            console.log("height" in f);  // true
  1. 需求: 判断某一个对象自身是否拥有某一个属性
  • 特点: 只会去类中查找有没有, 不会去原型对象中查找
            class Font{
                length = 45;
            }

            Font.prototype.height = 60;

            let f2 = new Font();

            // 特点: 只会去类中查找有没有, 不会去原型对象中查找
            console.log(f2.hasOwnProperty("length")); // true

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

推荐阅读更多精彩内容