Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

javascript中的this指向 #15

Open
Abiel1024 opened this issue Jun 27, 2018 · 0 comments
Open

javascript中的this指向 #15

Abiel1024 opened this issue Jun 27, 2018 · 0 comments

Comments

@Abiel1024
Copy link
Owner

Abiel1024 commented Jun 27, 2018

this是什么

this是 JavaScript 语言的一个关键字。
它是函数运行时,在函数体内部自动生成的一个对象,只能在函数体内部使用。
函数的不同使用场合,this有不同的值。总的来说,this就是函数运行时所在的环境对象。

this指向

1.纯粹的函数调用
在非严格模式下,this指向windows:

var x = 1;
function test() {
  console.log(this.x);
  test1() // 1
}
test();  // 1
function test1(){
  console.log(this.x)
}

在严格模式下,this值为undefined:

function test() {
  console.log(this); 
}
test();  // undefined 

2.作为对象方法的调用
函数还可以作为某个对象的方法调用,这时this就指这个上级对象。也就是我们平时说的,谁调用,this就指向谁。

var obj = {};
obj.x = 1;
obj.m = function test() {
    console.log(this.x);
};

obj.m(); // 1

3.作为构造函数调用
通过构造函数,new一个新的实例,这时this就指这个新实例。

function test() {
  this.x = 1;
}

var obj = new test();
obj.x // 1

4.apply、call、bind的使用
apply与call是函数的方法,作用是改变函数的调用对象。它的第一个参数就表示改变后的调用这个函数的对象。因此,这时this指的就是这第一个参数。
var obj = {
name: 'linxin'
}

function func() {
  console.log(this.name);
}

func.call(obj); //linxin
func.apply(obj); //linxin

bind也是函数的方法,作用也是改变this执行,同时也是能传多个参数。与call和apply不同的是bind方法不会立即执行,而是返回一个改变上下文this指向后的函数,原函数并没有被改变。并且如果函数本身是一个绑定了 this 对象的函数,那 apply 和 call 不会像预期那样执行

var obj = {
  name: 'bob'
}
function func() {
  console.log(this.name) 
}
var newObj= {
  name: 'jack'
}
var func1 = func.bind(obj,'linxin');
 func.call(obj );     //bob
func.call(newObj);     //jack
func1();         //bob
func1.call(newObj);     //bob

5.箭头函数
箭头函数没有自己的 this 绑定。箭头函数中使用的 this,其实是直接包含它的那个函数或函数表达式中的 this。可以参考MDN上的描述

const obj = {
  test() {
    const arrow = () => {
      // 这里的 this 是 test() 中的 this,
      // 由 test() 的调用方式决定
      console.log(this === obj);
    };
    arrow();
  },

  getArrow() {
    return () => {
      // 这里的 this 是 getArrow() 中的 this,
      // 由 getArrow() 的调用方式决定
      console.log(this === obj);
    };
  }
};

obj.test();     // true

const arrow = obj.getArrow();
arrow();        // true

可以看到这里两个this其实都是箭头函数的直接层函数决定的,而不是调用对象决定的。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant