var a = 1 functionfn() { var a = 2 console.log(this.a) // 等同于window.a, 输出1 } fn()
// -------------- 变 ----------------- // 1. 把最外层 var a = 1 -> let a = 1,输出结果是? // Answer: undefined. let 声明了自己的作用域,没有绑定到全局 // -------------- 变 ----------------- var b = 1 functionouter () { var b = 2 functioninner () { console.log(this.b) // console what ? } inner() }
// Yes, it does work with `new (funcA.bind(thisArg, args))` if (!Function.prototype.bind) (function(){ varArrayPrototypeSlice = Array.prototype.slice; // 为了 this Function.prototype.bind = function(otherThis) { // 调用者必须是函数,这里的 this 指向调用者:fn.bind(ctx, ...args) / fn if (typeofthis !== 'function') { // closest thing possible to the ECMAScript 5 // internal IsCallable function thrownewTypeError('Function.prototype.bind - what is trying to be bound is not callable'); }
// 1. functionfoo() { console.log( this.a ) // console what -> 2,相当于全局执行 } var a = 2; (function(){ "use strict"// 迷惑大家的 foo(); })();
// 2. var name="the window"
var object={ name:"My Object", getName: function(){ returnthis.name } } object.getName() // console what => my object (object.getName)() // console what => my object (object.getName = object.getName)() // console what => the window (=运算符丢失了this指向) (object.getName, object.getName)() // console what => the window
// 3. var x = 3 var obj3 = { x: 1, getX: function() { var x = 5 returnfunction() { returnthis.x }(); // ⚠️ } } console.log(obj3.getX()) // console what? => 3 IIFE函数丢失this指向,所以指向全局x
// 4. functiona(x){ this.x = x returnthis } var x = a(5) // 替换为 let 再试试 var y = a(6) // 替换为 let 再试试 // 再换回 var,但是去掉 y 的情况,再试试
console.log(x.x) // console what ? => undefined console.log(y.x) // console what ? => 6
Execution context (abbreviated form — EC) is the abstract concept used by ECMA-262 specification for typification and differentiation of an executable code.