the 4 point about This:
1.the use of Object methods
2.the use of constructors
3.the use of ordinary function
4.the use of Function.prototype.call or Function.prototype.apply
<!DOCTYPE html> <html> <head lang="en"> <meta charset="UTF-8"> <title>this of point</title> <script> /*the use of Object methods*/ var func={ a:2, getA:function(){ alert(this.a); } }; func.getA(); /*the use of ordinary function*/ window.name=‘globle‘; var getNaem=function(){ return this.name; }; alert(getName()); /*the use of constructors*/ var myClass=function(){ this.name=‘seven‘; }; var obj=new myClass(); alert(obj.name); /*warning: var myClass=function(){ this.name=‘seven‘; return{ name:‘jack‘; } }; var obj=new myClass(); alert(obj.name);//jack 如果构造器内部显式的返回了一个对象,那么次运算最终返回这个对象; */ /*the use of Function.prototype.call or Function.prototype.apply*/ var obj1={ name:‘seven‘, getName:function(){ return this.name; } }; var obj2={ name:‘jezz‘ }; alert(obj1.getName()); alert(obj1.getName.call(obj2)); </script> </head> <body> <div id="div1"></div> </body> <script> /*expanding*/ window.id=‘window‘; document.getElementById(‘div1‘).onclick=function() { alert(this.id);//div1 var callback = function () { alert(this.id);//window }; callback(); }; /* how to handle about this of point is changed*/ /*Approach 1: keeps this for variables*/ window.id=‘window‘; document.getElementById(‘div1‘).onclick=function() { var that=this; var callback = function () { alert(that.id);//div1 }; callback(); }; /* Approach 2:ues ‘call‘ change*/*/ window.id=‘window‘; document.getElementById(‘div1‘).onclick=function() { var callback = function () { alert(this.id);//div1 }; callback.call(this); }; </script> </html>
时间: 2024-10-05 03:54:02