Solo  当前访客:1 开始使用

关于this作用域


一、作为函数调用

function a(){
 this.p1 = 1;
 console.log(this)//window
}

a();//console.log:Window
window.p1 = 1;//验证

--作为函数调用时 即a(),结果为Window对象

二、作为某个对象的属性方法调用

function a(){
 //this.p1 = 1;//如果不注释,此p1将覆盖b的p1
 console.log(this.p1);//this:b

}

var b={};
b.p1 = 2;
b.m=a;

b.m();//2

b.p1;//2

三、作为构造函数使用时

function a(){
 this.p1 = 1;
 console.log(this);//值new出来的新对象 a1
  console.log(this === a);//false
  console.log(this instanceof a)//true
}

var a1 = new a();

四、apply调用时

var p1 = 1
function a(){
  console.log(this);
 console.log(this.p1);
}

var b={};
b.p1 = 2
b.m=a;

b.m.apply();//输出window,1
b.m.apply(b);//输出b,2
a.apply(b);//输出b,2

四、call调用

function c(){
  this.cp = 1;
  console.log(this); 
}

function a(){
this.ap = 1;
c.call(this);
}

var a1 = new a();//console:new出的a的新对象。a1{ap:1,cp:1}


标题:关于this作用域
作者:hugh0524
地址:https://blog.uproject.cn/articles/2016/06/24/1466766186089.html

, , , 0 0