- 函数预编译后 this = window
- 全局的 this = window
- function.call(obj) / function.apply(obj) : this = obj
- obj.function(); 函数体里面的 this = obj
function a() {return this}
var b = a();
var c = new a();
var d = this;
var e = a.call({name : 'chl'});
var f = {
fAttr : function () {
return this
}
}
// b = {parent: Window, opener: null, …} // = window
// c = a { // = a.prototype
// __proto__ : {
// constructor : a,
// __proto__ : {...}
// }
// }
// d = {parent: Window, opener: null, …} // = window
// e = {
// name : 'chl',
// __proto__ : {...}
// }
// f.fAttr() = { // = f
// fAttr : ƒ (), // = function () {return this}
// __proto__ : {...}
// }
- 练习
var name = '222';
var a = {
name : '111',
say : function () {
console.log(this.name);
}
}
var fun = a.say; // = function () {console.log(this.name);}
fun(); // this = window // window.name = '222'
a.say(); // this = a // a.name = '111'
var b = {
name : '333',
say : function (fun) {
fun();
}
}
b.say(a.say);
// b.say = function (fun) { // fun = function () {console.log(this.name);}
// this = b
// fun(); // this = window // window.name = '222'
// }
b.say = a.say; // b.say = function () {console.log(this.name);}
b.say(); // this = b // b.name = '333'
// console.log 输出:
// 222
// 111
// 222
// 333