index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<script src="test.js"></script>
</body>
</html>
test.js
var a = 2;
function t1() {
console.log("this.a", this.a);
}
var obj = {
a: 3,
q: function () {
console.log("this", this);
t1();
},
p: t1,
};
var f = obj.q;
var f2 = obj.p;
t1();
obj.q();
obj.p();
f();
f2();
// 浏览器环境
// this.a 2
// test.js:10 this {a: 3, q: ƒ, p: ƒ}
// test.js:4 this.a 2
// test.js:4 this.a 3
// test.js:10 this Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
// test.js:4 this.a 2
// test.js:4 this.a 2
// nodejs环境
// this.a undefined
// this { a: 3, q: [Function: q], p: [Function: t1] }
// this.a undefined
// this.a 3
// this Object [global] {
// global: [Circular *1], }
// this.a undefined
// this.a undefined
// 浏览器环境
// 上面的可以写成下面的
// t1.bind(window)();
// obj.q.bind(obj)();
// obj.p.bind(obj)();
// f.bind(window)();
// f2.bind(window)();
// this.a 2
// test.js:10 this {a: 3, q: ƒ, p: ƒ}
// test.js:4 this.a 2
// test.js:4 this.a 3
// test.js:10 this Window {parent: Window, opener: null, top: Window, length: 0, frames: Window, …}
// test.js:4 this.a 2
// test.js:4 this.a 2
var myObject = {
foo: 'bar',
func: () => {
var self = this;
console.log('outer func: this.foo=' + this.foo); // undefined
console.log('outer func: self.foo=' + self.foo); // undefined
(function() {
console.log('inner func: this.foo=' + this.foo); // undefined
console.log('inner func: self.foo=' + self.foo); // undefined
})();
}
};
myObject.func();