JavaScript全局角度看this

    科技2024-05-20  80

    <script charset="utf-8"> //在没有进行任何初始化的时候,this就是window对象 console.log(this); //构造函数或任何函数或在函数以外中出现的this,其实都指的是window this.document.write("大家好,我是使用的this.document.write显示的文字") function Caculator(){ this.aaplus = function(op1,op2){ console.log("相加的结果为" + (op1+op2)); } this.aamul = function(op1,op2){ console.log("相乘的结果为:" + op1 * op2) } aadivid = function(op1,op2){//如果不加this,也不加var的话,暗示为全局变量,即将该 //方法名或变量名加到window中 console.log("相除的结果为:" + op1 / op2) } var aasub = function(op1,op2){ console.log("相减的结果为:"+ (op1 - op2)) } } Caculator(); aaplus(1,2); aadivid(2,2) //将把该函数中的带有this的属性和方法自动添加到对象中去,aadivid()方法没有this则该对象没有加到对象中 var cal = new Caculator();//当构造函数前面有new关键字时, cal.aaplus(1,2); console.log(cal); </script>
    Processed: 0.009, SQL: 8