函数内部 this 指向

构造函数 this 指向实例化对象

function Test() {
  //var this = {
	//	__proto__: Test.prototype
	//}
	this.name = '123';
}
var test = new Test();

AO = {
	this: window -> {
    __proto__: Test.prototype,
    name: '123'
  }
}
GO = {
	Test: f() {},
  test: {}
}

call/apply 改变 this 指向

function Person() {
	this.name = 'Lance';
	this.age = 10;
}
function Programmer() {
	Person.apply(this);
	this.work = 'Programming';
}
var p = new Programmer();
console.log(p);

Untitled

🌈 闭包、箭头函数、setTimeout 中 this

var x = {
  name: 'bw2',
  getName1: function() {
    console.log(this)
  },
  getName2: function() {
    setTimeout(() => {
      console.log(this)
    },0)
  },
  getName31: () => {
    console.log(this)
  },
  getName32: function() {
    return function() {
      console.log(this)
    }
  }
}
x.getName1();

// {name: "bw2", getName1: ƒ}
// x为调用者

x.getName2()
// {name: "bw2", getName1: ƒ}
// 箭头函数没有this,this继承外层作用域,
// x为getName2调用者,this指向x

x.getName31()
// Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}
// js中作用域只有全局作用域和函数作用域
// 箭头函数this指向外层作用域window,而不是调用者x

x.getName32()()
// Window {stop: ƒ, open: ƒ, alert: ƒ, confirm: ƒ, prompt: ƒ, …}
// this的值取决于调用上下文,
// 如果一个函数不是作为某个对象的方法被调用,
// 那么this就是global object.否则就是该对象

🌈 callee/caller

arguments.callee 返回正在被执行的函数

function test(a, b, c) {
	console.log(arguments.callee.length); // === test.length = 3
	console.log(arguments.callee); // function test
}
test(1, 2, 3);

Untitled

callee 的应用 - 匿名函数递归调用

var sum = (function (n) {
  if (n <= 1) return 1;
	return n + arguments.callee(n - 1);
})(100);

console.log(sum); // 5050

Function.caller 返回调用指定函数的函数

function test1() {
	test2();
}
function test2() {
	console.log(test2.caller);
}
test1();

Untitled