2020前端

JS 关键字 instanceof 和 isPrototype

2020-03-19  本文已影响0人  超级皮波9

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

           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 的注意点

            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. 判断某一个对象是否拥有某一个属性
            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
上一篇 下一篇

猜你喜欢

热点阅读