JavaScript执行运行时 再解(三)

函数

分类

  1. function foo() {
    	// code
    }
    
  2. const foo = () => {
    	// code
    }
    
  3. class C {
    	foo() {
    		// code
    	}
    }
    
  4. function* foo() {
    	// code
    }
    
  5. class Foo {
    	constructor() {
    		// code
    	}
    }
    
  6. async function foo() {
    	// code
    }
    async foo = async () => {
      // code
    }
    async function foo* () {
      // code
    }
    

this

this是执行上下文中很重要的一个组成部分。我们使用 React 开发应用的时候就深有体会,class 与 function 组件的 this 是截然不同的,普通 function 与箭头function 的 this 也是完全不一样的。

function showThis() {
	console.log(this);
}
var o = {
  showThis: showThis,
}
showThis();	// window
o.showThis();	// o

我们获取函数的表达式,它实际上返回的并非函数本身,而是一个 reference 类型。

引用类型,就是一个 kv 对,通过 点 或者 方括号来引用。

调用函数时候使用的引用,就决定了函数执行时刻的 this 值。

const showThis = () => {
    console.log(this);
}

var o = {
    showThis: showThis
}

showThis(); // global
o.showThis(); // global

箭头函数的 this 就完全不受影响。

class C {
    showThis() {
        console.log(this);
    }
}
var o = new C();
var showThis = o.showThis;

showThis(); // undefined
o.showThis(); // global

调用函数时候使用的引用决定 this,我们直接使用 showThis的时候,没有对象来引用它,所以出来一个 undefined。

call、bind、apply

Function.prototype.call 还有 Function.prototype.apply可以指定函数调用的时候传入的 this 值。

function foo(a,b,c) {
	console.log(this);
	console.log(a,b,c);
}
foo.call({}, 1, 2, 3);
foo.apply({}, [1, 2, 3]);

在这个地方,call 与 apply 作用相同,传参不同。

还有一个Function.prototype.bind,它可以生成一个绑定过的函数,这个函数的 this 值固定了参数:

function foo(a,b,c) {
	console.log(this);
	console.log(a,b,c);
}
foo.bind({}, 1, 2, 3)();
原文地址:https://www.cnblogs.com/ssaylo/p/13156389.html