this

作者: 米卡卡米 | 来源:发表于2018-09-17 20:07 被阅读0次

    关于This
    【不懂this是因为不用call】【放应杭 this】
    f.call(asthis,input1,input2) this就是第一个参数
    如果不知道this,就换成call的形式
    比如:itme1.getSiblings(p1,p2) ==>itme1.getSibings.call(item1,p1,p2)
    func(p1, p2) 等价于func.call(undefined, p1, p2)
    //如果是用一个对象,去调用一个函数,那么这个对象就是这个函数里面的this

    函数调用只有一种形式(其他的也转换成这种):func.call(context, p1, p2)
    那么 this的值,就是上面代码中的 context
    【理解this的指向问题】
    this的指向在函数定义的时候是确定不了的,只有函数执行的时候才能确定this到底指向谁,实际上this的最终指向的是那个调用它的对象
    DOM对象绑定事件也属于方法调用模式,因此它绑定的this就是事件源DOM对象

    document.addEventListener('click', function(e){
        console.log(this);//输出document对象
    }, false);
    

    函数调用模式:1.普通调用。

    function f1(){
    console.log(this)//Window
    }
    

    2.函数嵌套

    function f1(){
    function f2(){
    console.log(this)//Window
    }
    }
    

    3.把函数赋值后再调用

    var a=1
    var obj1={
    a:2,
    fu:function(){
    console.log(this.a)}
    }
    var fn1=obj1.fn
    fn1();
    

    解析:fn1=function(){console.log(this.a)}==>console.log(this.a).call(undefined)
    所以是undefined

    如果你传的 context 就 null 或者 undefined,那么 window 对象就是默认的 context(严格模式下默认 context 是 undefined)
    因此上面的this绑定的就是window,它也被称为隐性绑定。
    如果想要修改绑定。可以用fn1.call(obj1) 那值会等于1
    4.回调函数

    var a = 1
    function f1(fn){
        fn()
        console.log(a)//1
    }
    f1(f2)
    function f2(){
        var a = 2
    }
    //简化一下 f1(f2) f2=fn 所以fn替换成f2内容
    var a=1
    function f1(){
    (function f2(){var a=2})()
    console.log(a)//1
    }
    f1()
    

    构造器调用模式:

    new一个函数时,背地里会将创建一个连接到prototype成员的新对象,同时this会被绑定到那个新对象上

    function Person(name,age){
    // 这里的this都指向实例
        this.name = name
        this.age = age
        this.sayAge = function(){
            console.log(this.age)
        }
    }
    
    var dot = new Person('Dot',2)
    dot.sayAge()//2
    

    虽然不理解 但是先复制过来 再看。

    相关文章

      网友评论

          本文标题:this

          本文链接:https://www.haomeiwen.com/subject/grldnftx.html