zoukankan      html  css  js  c++  java
  • Javascript四种调用模式中的this指向

    第一种:函数直接调用执行的模式

    function add(a,b){  
        console.log(this);   
        return a+b; 
    }
    add(1,2)
    //this===window 这里的this指向是window的

    第二种:对象方法的调用模式

    var people={  
        name:'wang',   
        sex:'',  
        eat:function(){    
            console.log(this);   
        }  
    }
    people.eat();
    //this===对象,对象方法调用时,this指向被调用者   

    第三种:构造器的调用模式

    function People(){  
        this.eat=function(){   
            console.log(this);   
        }  
    }
    var wang=new People();
    wang.eat();
    //对象调用自己的方法,this===wang,谁new的this指向谁

    第四种:call和apply调用模式

      call方法有多个参数,第一个是要绑定给this的值,后面跟是若干。

      apply方法有两个参数,第一个是要绑定给this的值,第二个是一个参数数组可以放若干。

     function change(a,b){
         this.detial=a*b;
         console.log(this);
    }
    var p={};
    change.call(p,4,5);//此处的this===p
    console.log(p.detial);
    var q=[];
    change.call(q,5,10)//this===q
    console.log(q.detial);
    
    //apply和call一样的用法,只不过apply第二个参数用数组进行传递
    var arr=[];
    change.apply(arr,[10,10]);//this===arr
    console.log(arr.detial);
    
    var str={};
    change.apply(str,[20,20]);//this===str
    console.log(str.detial);
                 
  • 相关阅读:
    构建之法阅读笔记05
    构建之法阅读笔记04
    构建之法阅读笔记03
    构建之法阅读笔记02
    构建之法阅读笔记01
    管理系统的简单解析---web
    Java中的异常处理
    多态
    重写与重载
    抽象类与接口
  • 原文地址:https://www.cnblogs.com/wangmaoling/p/6535801.html
Copyright © 2011-2022 走看看