Javascript修正this的引用

1.使用this作为参数来传递给函数。因为this始终与当前对象一致。

 1 <!DOCTYPE html>
 2 <html>
 3      <head>
 4     <meta charset=utf-8 />
 5     <title>js</title>
 6     <script>
 7          function f(){
 8             alert(this.value);
 9          }
10 
11          function f2(o){
12             alert(o.value);
13          }
14     </script>                
15      </head>
16 
17      <body>
18         <input type="button" value="value1" onclick="f()"/>       //undefined   this指向window对象,而不是button对象
19         <input type="button" value="value2" onclick="f()"/>       //undefined
20         
21         <input type="button" value="value3" onclick="f2(this)"/>      //value3
22         <input type="button" value="value4" onclick="f2(this)"/>       //value4
23         
24      </body>
25 </html>

2.把this变量存储在私有变量中,然后在方法中使用私有变量来引用this指针。

 1      function Base(){
 2             this.name = 'Base';
 3 
 4             var _this = this;        //用私有变量存储this 
 5           
 6             //私有方法
 7             function alertName(){
 8                 alert(this.name);   
 9             }
10 
11             function alertName2(){
12                 alert(_this.name);      //使用私有变量
13             }
14             // 公共方法
15             this.concat = function(message){
16                 this.name += message;
17                  //alertName();   //不能得到name+message
18 alertName2(); 19 } 20 21 } 22 var b = new Base(); 23 24 b.concat('hello');

这种方法也可以用在继承中。

 1         function Base(){               //基类
 2             this.name = 'Base';
 3 
 4             var _this = this;
 5             this.m = function(){
 6                 return _this;
 7             }
 8          }
 9          var b = new Base();
10 
11          function F(){           
12             this.name = 'F';
13          }
14 
15          F.prototype = new Base();    //继承
16          var f = new F();
17          alert(f.name);    //F
18 
19          var n = f.m();
20          alert(n.name);    // Base

3.使用apply或call改变函数的执行环境。

1    function f(){
2        alert(this.x + this.y);
3    }
4     var obj = {x:1,y:2};
5     f.call(obj);         //3
    /*定义一个人类*/
    function Person(name,age)
    {
        this.name=name;
        this.age=age;
    }
    /*定义一个学生类*/
    functionStudent(name,age,grade)
    {
        Person.apply(this,arguments);
        this.grade=grade;
    }
    //创建一个学生类
    var student=new Student("qian",21,"一年级");
    //测试
    alert("name:"+student.name+"
"+"age:"+student.age+"
"+"grade:"+student.grade);
    //大家可以看到测试结果name:qian  age:21  grade:一年级
    //学生类里面我没有给name和age属性赋值啊,为什么又存在这两个属性的值呢,这个就是apply的神奇之处.

4.总结:感觉js也很强大,js真是大屌丝一个。

原文地址:https://www.cnblogs.com/yuyutianxia/p/3261149.html