1.this 指向它的调用对象
- function getA(){
- var a = 1;
- console.log(this); //Windows
- console.log(this.a); //undefined
- }
- getA(); // 等价于 Windows.getA()
- var getA={
- a:"1",
- fn:function(){
- console.log(this.a) //1
- }
- }
- getA.fn(); // 此时 this 指向对向 getA
- var getA={
- a:1,
- fn:function(){
- console.log(this.a) //1
- }
- }
- Windows.getA.fn(); // 此时 this 仍然指向 getA(),this 只会指向他的上一级
- var getA={
- a:1,
- b:{
- a:5,
- fn:function(){
- console.log(this.a); //5
- }
- }
- }
- getA.b.fn();
- var getA={
- a:1,
- b:{
- a:5,
- fn:function(){
- console.log(this.a); //undefined
- }
- }
- }
- var c = getA.b.fn;
- c(); //fn 赋值给变量 C 时没有执行, 所以最终指向是 Windows
2.new 会改变 this 的指向
- function getA(){
- this.a = 1;
- }
- var b = new getA();
- console.log(b.a); //1,new 等于将 getA() 复制了一份到对象 B 中
- function getA(){
- this.a = 1;
- return{
- };
- }
- var b = new getA();
- console.log(b.a); //undefiend
- function getA(){
- this.a = 1;
- return function(){
- };
- }
- var b = new getA();
- console.log(b.a); //undefiend
- function getA(){
- this.a = 1;
- return 1;
- }
- var b = new getA();
- console.log(b.a); //1
- function getA(){
- this.a = 1;
- return undefined;
- }
- var b = new getA();
- console.log(b.a); //1
- function getA(){
- this.a = 1;
- return null;
- }
- var b = new getA();
- console.log(b.a); //1
3.call,apply 会改变 this 指向
- var getA={
- a:1,
- fn:function(){
- console.log(this.a);
- }
- }
- var b = getA.fn;
- b.call(getA);
call 可以添加多个参数
- var getA={
- a:1,
- fn:function(c,d){
- console.log(this.a); //1
- console.log(c+d); //7
- }
- }
- var b = getA.fn;
- b.call(getA,3,4);
apply 与 call 类似, 但是 apply 的第二个参数必须是数组
- var getA={
- a:1,
- fn:function(){
- console.log(this.a); //1
- }
- }
- var b = getA.fn;
- b.apply(getA);
- var getA={
- a:1,
- fn:function(c,d){
- console.log(this.a); //1
- console.log(c+d); //7
- }
- }
- var b = getA.fn;
- b.call(getA,[3,4]);
如果 call 和 apply 的第一个参数写的是 null, 则指向 Windows
来源: http://www.bubuko.com/infodetail-3156471.html