【转】JavaScript中的this关键字使用的四种调用模式

http://blog.csdn.net/itpinpai/article/details/51004266

this关键字
本意:这个、这里的意思.
在JavaScript中是指每一个方法或函数都会有一个this对象,this对象是方法(或函数)在执行时的那个环境,也可以说是这个函数在那个作用域下运行的

一共有四种调用模式:方法调用模式(对象属性模式)、函数调用模式(就是普通的函数执行)、构造调用模式(应该叫实例上的方法模式更好)和apply调用模式。

一、方法调用模式
当它为一个对象上的方法的时候,this是当前这个对象

function age() { alert(this); }
var person = new Object();
person.age = age;
这里的this指向的就是创建的这个person对象

二、函数调用模式
当函数并非一个对象的属性时,那么它被当做一个函数来调用。此模式下this绑定到全局对象
var a = 1;
function fn() {
  console.log( this.a );
}
fn(); // 1 
fn函数中的this指定的是全局对象,全局对象是window

三、构造函数调用模式
在构造函数里的this是指向这个对象

function  Person( age ) {
  this.age = age;
}
var person = new Person(15);
console.log(person.age); // 15

四、apply调用模式
apply是把一个函数当成另一个对象的方法来调用

function age() {
  console.log(this.age);
}
function Person() {
  this.age = 18;
}
var person =  new Person();
age.apply(person); // 18

一.函数调用,此时this是全局的也就是window
  var c=function(){
   alert(this==window)
  }
  c()//true

二.方法调用
 var myObj={
  value:2,
  inc:function(num){
   alert(this.value+num);
  }
 }

 myobject.inc(1); //结果3,因为this指向myObj

注意:内部匿名函数不属于当前对象的函数,因此this指向了全局对象window

var myObj={
   name:'myObject',
   value:0,
   increment:function(num){
    this.value += typeof(num) ==='number'? num:0;
   },
   toString:function(){
    return '[object:'+this.name+'{value:'+this.value+'}]';
   },
  
   getInfo:function(){
      return (function(){
        return this.toString();//内部匿名函数不属于当前对象的函数,因此this指向了全局对象window
      })();
  }
 }
alert(myObj.getInfo());//[object window];
点击看结果
解决方法:
 var myObj={
  name:'myObject',
  value:0,
  increment:function(num)   {
   this.value += typeof(num) ==='number' ? num : 0;
  },
  toString:function()   {
    return '[object:'+this.name+'{value:'+this.value+'}]';
  },
  getInfo:function(){
   var This=this;//先把当前的this指向存起来
   return (function(){ 
      return This.toString();
   })();
  }
 }
alert(myObj.getInfo());//[Object:myObject {value:0}]
点击看结果 三.用new关键字来新建一个函数对象的调用,this指向被绑定到构造函数的实例上 var fn = function (status){ this.status = status; } fn.prototype.get_status = function(){ return this.status; } var test = new fn('my status'); alert(test.get_status);//my status,this指向test 四.apply/call调用 function MyObject(name){ this.name=name ||'MyObject'; this.value=0; this.increment=function(num){ this.value += typeof(num) === 'number' ? num : 0; }; this.toString=function(){ return '[Object:'+this.name+' {value:'+this.value+'}]'; }; this.target=this; } function getInfo(){ return this.toString(); } var myObj=new MyObject(); alert(getInfo.apply(myObj));//[Object:MyObject {value:0}],this指向myObj alert(getInfo.apply(window));//[object Window],this指向window 通过call和apply可以重新定义函数的执行环境,即this的指向,这对于一些应用当中是十分常用的。 点击看结果
原文地址:https://www.cnblogs.com/mimime/p/5890907.html