javascript总结38: 神奇的this

时间:2023-03-08 21:46:05

1 this的特性

this 是在函数中的
this 的指向 是在函数调用的时候决定的
this的指向. 谁调用这个函数,函数中的this就指向谁

 function fn (){
console.log(this);
} // fn(); //this --> window var obj = {};
obj.f = fn;
obj.f(); //this -->obj

2 与this相关的new关键字

var instance = new fn();

new 做的四件事情:
1. 在内存中创建了一个新的空对象
2. new 调用了这个函数
3. new 让函数中的this指向刚才创建出来的新对象
4. 返回这个新的对象

window.fn();
window.alert() window.fn = function(){
console.log(this);
} console.log(window);
var a = 1;
console.log(window.fn);
var a = 1;
window.a = 1;