关于 this对象 指向问题

 this 定义:this是包含它的函数作为方法被调用时所属的对象。(1,this所在的函数。2,此函数作为方法被调用。3,this等于调用此函数的对象)

this 对象在运行时基于函数的执行环境绑定的。在全局环境中this等于window,当函数作为某个对象的方法调用时,this等于那个对象。所以说,this的指向完全

取决于函数的调用方式。

1》函数的四种调用方式

  1.函数调用模式

function fn() {console.log(this)}
fn(); //window

this是全局对象(window)

2.方法模式

var obj = {
   a: function() {console.log(this)}
};

obj.a(); //this指向obj

this是当前调用方法的对象

3. 构造器模式(constructor)

  function Fn() {this}//this指向p
   var p = new Fn();

function Point(x, y){ 
    this.x = x; 
    this.y = y; 
 }

 this指向新创建出来的对象

 

4上下文模式 (通过call或apply改变函数执行环境的情况下 ,this 也会指向其他对象)

     1.函数名.apply(this指向的对象,[参数1, 参数2, ...])    

      function foo() {console.log( this );}
        foo.apply();//this指向window
        foo.apply( null );//this指向window
         var o = { name: 'aaa' };
       foo.apply( o );//this指向o,用o调用foo  

2. 函数名.call(this指向的对象,参1,参2...);

       call和apply的区别  apply的第二个参数是数组形式,call第二个参数是单个参数分开传入

   例子:

 

 function Point(x, y){ 
    this.x = x; 
    this.y = y; 
    this.moveTo = function(x, y){ 
        this.x = x; 
        this.y = y; 
    } 
 } 

 var p1 = new Point(0, 0); 
 var p2 = {
x: 0,
y: 0
}; p1.moveTo(1, 1); p1.moveTo.apply(p2, [10, 10]);
我们看到使用 apply 可以将 p1 的方法应用到 p2 上,这时候 this 也被绑定到对象 p2 上

 

2》在闭包中如果把外部作用域中的this对象保存在一个闭包能够访问到的变量里面。就可以让闭包访问该对象。

   var name='jim';var obj={
    name:'tom',
    getName:function(){
        var that=this;
        return function(){
            return that. name;
        }
    }
}
alert(obj.getName()())//'tom'
 that是在包含函数中特意声明的变量  它指向的obj

3》语法的细微变化 也会引起this的变化

  var name='jim';
var obj={
    name:'tom',
    getName:function(){
            return this. name;
    }
}
obj.getName() // tom
(obj.getName=obj.getName)()//jim
     第二个打印进行了一次赋值操作   所谓赋值
    如果a=b=function(){} 先将函数赋值给b 再将函数赋值给a

  在例子中 (a=b)它是赋值后的结果 也就是函数本身 调用函数本身 则此时this指向window.

 

 

posted @ 2016-04-16 00:40  好好听我说  阅读(328)  评论(0编辑  收藏  举报