文章目录
this
函数预编译过程this --> window
function test(num) {
var a = 123;
function test1() { };
}
test(1);
- 上述函数预编译过程中形成test的AO
AO{
test1 : function,
a : undefined,
num : 1
}
其中还包含
{
this : window,
arguments : [1]
}
此时,this指向window
全局作用域里this --> window
- 当直接在全局中访问this时,此时this --> window
call/apply可以改变函数运行时this的指向
obj.function();function()里面的this指向obj
var test = {
a : function() {
console.log(this.name)
},
name : '123'
}
test.a();
// 结果为123,此时this指向test
// test调用a函数,所以函数中this指向test
- example
var name = '123';
var a = {
name : '456',
say : function () {
console.log(this.name)
}
}
var fun = a.say;
fun(); //123
a.say(); //456
var b = {
name : '789',
say : function(fun) {
fun();
}
}
b.say(a.say); //123
b.say = a.say;
b.say(); //789
当执行fun()时,此时fun = a.say,方法中的this指向window,此时结果为123
当执行a.say时,a调用say方法,此时this指向调用函数a,a.name = 456
当执行b.say(a.say)时b.say调用a.say方法,this指向b.say,b.say没有name属性,所以沿着原型链到全局中找name属性得到全局变量name = 123
当执行b.say()时,b调用say方法,this指向b,b.name = 789
arguments
arguments.callee
function test() {
console.log(arguments.callee);
}
test()
// 结果:
// ƒ test() {
// console.log(arguments.callee);
// }
- 应用
var num = (function (n) {
if (n == 1) return 1;
else return n * arguments.callee(n - 1)
}(10))
console.log(num)
计算10的阶乘
function.caller
- 谁调用返回谁
function test() {
demo();
}
function demo() {
console.log(demo.caller)
}
test();
// 结果:
// ƒ test() {
// demo();
// }