浅谈JavaScript--this指向

js中this的值取决于调用的模式

  • 方法调用模式
var student={
    name:"adoctors",
    showThis:function(){
        console.log(this);          //此处this为整个student对象,包括其中的属性和方法
        console.log(this.name);   // 'adoctors'
    }
}
  • 函数调用模式
function fn(){
    console.log(this);   //this指向window对象
    
    var name = "adoctors";
    console.log(this.name);   //undefined
    
    //也可通过赋值变量改变this指向
    var that=this;
    ···
}
  • 构造器调用模式
var fn = function (status){
    this.status = status;
}
fn.prototype.get_status = function(){
    return this.status;
}
var test = new fn('my status');
console.log(test.get_status);   //my status,this指向test
 
  • apply和call调用模式
function foo(){
    console.log(this.fruit);
}
// 定义一个全局变量,等同于window.fruit = "banana";
var fruit = "banana";

var  o = {
    fruit : "apple"
};
    
foo.apply(window);  // "banana";
foo.call(o);  // "apple";

apply和call的唯一区别,就是在传参的时候,apply的参数需要放在一个数组里面,而call不需要;

posted @ 2018-03-04 20:02  adoctors  阅读(156)  评论(0编辑  收藏  举报