全局中指向windowjavascript
函数预编译过程时指向windowjava
call apply改变this指向(在上一篇博客中详细说起了他们两个的做用今天就不包含在实际案例之中)app
对象调用方法this的指向函数
var name= "222";
var a = {
name : "111",
say : function() {
console.log(this.name);
}
}
var fun = a.say;
fun();
a.say();
var b = {
name : "333",
say : function(fun){
fun();
}
}
b.say(a.say);
b.say = a.say;
b.say();
复制代码
按照以前所总结的答案很显然22二、1十一、22二、333。ui
很差理解的点可能在于b.say(a.say),这句语句至关于实现了把a中的方法放到b的say方法中调用,注意调用二字,b中say方法执行时只是在全局中执行了fun函数,而不是说b对象运行了fun函数中的代码。因此结果是222。this
构造函数与函数this指向区别咱们来看个案例spa
var a = 5;
function test() {
console.log(a);
a = 0;
console.log(this.a);
var a;
console.log(a);
}
console.log(test()); // undefined、五、0
console.log(new test()) // undefined、undefined、0
复制代码
这边又再次复习了一下与预编译的实现实现1时,函数中预编译环节this指向window因此输出5 执行2时,以前说起过构造函数生成对象时函数中会生成一个空的this对象(构造函数那篇有详细说明),那么这一次函数中this指向的是函数中的那个空this因此返回undefined。code
ending...对象