前端

51 阅读2分钟

原型和原型链

  1. 原型分为隐式原型和显式原型,每个对象都有一个隐式原型,它指向自己的构造函数的显式原型
  2. 原型链:多个_proto_组成的集合成为原型链
  3. 所有实例的_proto_都指向他们构造函数的prototype
  4. 所有的prototype都是对象,自然它的_proto_指向的是object()的prototype
  5. 所有的构造函数的隐式原型指向的都是function()的显示原型
    注:object的隐式原型是null

image.png

instanceof

  • instanceof 运算符用于检测构造函数的prototype属性是否出现在某个实例对象的原型链上。(判断继承关系)
  • 可以判断继承关系,只要是在同一条原型链上,就可以返回true

3604247935cc9963e40fe8117c180d0.png

     class Person {
        constructor(name){
            this.name = name;
        }
    }
     class Student extends Person {
        constructor(name,age){
            super(name);
            this.age = age;
        }
    }

    const zhangsan = new Student("张三",18);
    console.log(myInstanceof(zhangsan,Student));
    console.log(myInstanceof(zhangsan,Person));
    console.log(myInstanceof(zhangsan,Object));
    console.log(myInstanceof(zhangsan,Array));
    function myInstanceof(obj1,obj2) {
        let obj1Proto = obj1.__proto__;
        while(true){
            if(obj1Proto === null){
                return false;
            }
            if(obj1Proto === obj2.prototype){
                return true;
            }
            obj1Proto = obj1Proto.__proto__;
        }
    }

this指向

  • 普通函数中的this:
  1. 非严格模式 this -> window
    //非严格模式
    function a () {
        console.log(this);
    }
    a()
  1. 严格模式 this -> undefined
    // 严格模式下
    "use strict"
    function a() {
        console.log(this);
    }
    a()
  • call apply bind 中的this
  1. 情况一:this->window
    1) a.call()
    2) a.call(undefined)
    3)a.call(null)
    function a (){
        console.log(this);
    }
    a.call(null/undefined)
  1. 情况二:传什么,this就是什么
    function a (){
        console.log(this);
    }
    // a.apply("abc");
    const fn = a.bind({x:101});
    fn()
  • 定时器中的this
  1. 情况一:定时器+function this -> window
    function fn(){
        setTimeout(function(){
            console.log(this);
        },100)
    }
    fn.call({x:101}) //window
  1. 情况二:定时器+箭头函数 this -> 上层作用域的this
    class obj {
        fn(){
            setTimeout(()=>{
                console.log(this);
            },100)
        }
    }
    const o = new obj();
    o.fn();
  • 箭头函数中的this
  1. 情况一:有function作用域的,this是上层作用域的this(new一个作用域)
    class obj {
        say = () => {
            console.log(this);
        }
    }
    const obj1 = new obj();
    obj1.say() // obj {say: ƒ}
  1. 情况二:没有function作用域的,this是window
    const obj2 = {
        say:()=>{
            console.log(this);
        },
    }
    obj2.say();