【笔记16】Javascript - this
this
函数预编译过程中 this --> (指向)window;
全局作用域里 this -->window;
call / apply 可以改变函数运行时 this 指向;
obj.func(); func() 里面的this指向obj;
函数预编译过程中,this 指向 window 。
function test(c) {
var a = 123;
function b() {
}
}
// AO{
// arguments:[1],
// this: window, // 默认指向 window
// c:1,
// a:undefined,
// b:function(){}
//}
test(1);
测试一下:
function test(){
console.log(this); // window
}
test();
看控制台输出:
和自己打印个 window 效果一样。
如果这里是构造函数,要new的话,情况不太一样:
function test(c) {
// var this = Object.create(test.prototype);
var a = 123;
function b() {
}
}
// AO{
// arguments:[1],
// this: Object.create(test.prototype),
// c:1,
// a:undefined,
// b:function(){}
//}
new test(1);
要 new 了,this 被创建了一个原型,就指向 test.prototype 上去了。
全局作用域里 this 指向 window
console.log(this); // window
call / apply 可以改变函数运行时 this 指向
obj.func(); func() 里面的this指向obj;
谁调了这个方法,这里的 this 指向的就是谁。
var obj = {
a:function(){
console.log(this.name);
},
name:"abc"
}
obj.a(); // abc
obj 调用了 this,这里的 this 就指向 obj ,输出 : abc 。
如果是空执行呢,没人调用 this 呢?
function test(){
console.log(this);
}
test(); // window
没人调用就指向 window
以下两个,在 “use strict” 严格模式下不让用,看一看吧。
arguments.callee
是指向这个函数的引用,看代码:
function test(){
console.log(arguments.callee); // test
console.log(arguments.callee == test); // true
}
test();
arguments.callee 指向这个函数的引用,谁引用了他,他显示谁。
显示的就是 test 本身。这有啥用?
看一个立即执行函数里的应用:
var num = (function (n) {
if (n == 1) {
return 1;
}
return n * arguments.callee(n - 1); // 函数本身没有名字,就可以使用 arguments.callee了
}(10));
console.log(num);
这是个立即执行函数里的递归,自己要调用自己,但自己没有函数名,就可以用 arguments.callee 。
还有个问题:
function test(){
console.log(arguments.callee);
function demo(){
console.log(arguments.callee);
}
demo();
}
test();
arguments.callee 被哪个函数调用,就指向这个函数,函数里面套函数,哪个用就指向哪个:
test 调用了,就显示整个 test 函数;demo 调用了,就只显示 demo 函数;
func.caller
在哪个环境里被调用了,就显示哪个环境;
caller 不是arguments 的属性,arguments 上只有 length 和 callee 两个属性。 这个caller 是函数自己的属性,放在一起讲,是 func.caller 和 arguments.callee 喜欢一起考。两个属性看着也有点像。知识点有点偏;
function test(){
demo();
}
function demo(){
console.log(demo.caller);
}
test(); // test
demo 在哪里被调用的,就显示哪: