console.log(a); var a = 1;
a(); var a = function(){...};
func(); function func(){ console.log(1); } var func = function(){ console.log(2); } func();
function func(){ a = 1; console.log(window.a); // ? console.log(a); // ? var a = 2; console.log(a); // ? } func();
var people = { Name: "a", getName : function(){ console.log(this.Name); } }; var bar = people.getName; bar();
var people = { Name: "a", getName : function(){ console.log(this.Name); } }; people.getName();
var name = 'b'; var a = { name: 'a', getName: function() { console.log(this.name); } } var obj = a.getName; obj(); // ?
var name = 'b'; var a = { name: 'a', getName: function() { console.log(this.name); } } var obj = a.getName(); obj; // ?
var name = 'b'; var a = { name: 'a', getName: function() { console.log(this.name); } } a.getName.call(this);
var name = 'b'; var a = { name: 'a', getName: function() { console.log(this.name); } } var func = a.getName.bind(this); func();
var name = 'b'; function func() { this.name = 'a'; console.log(this.name); } var obj = new func(); obj; // ?
var name = 'b'; var people = { name: "a", getName : function() { return () => { console.log(this.name); } } }; var bar = people.getName(); bar();
function foo(arg){ this.a = arg; return this }; var a = foo(1); var b = foo(2); console.log(a.a); // ? console.log(b.a); // ?
var x = 1; var obj = { x: 2, f: function(){ console.log(this.x); } }; var bar = obj.f; var obj2 = { x: 3, f: obj.f } obj.f(); bar(); obj2.f();
function obj() { getName = function () { console.log (1); }; return this; } obj.getName = function () { console.log(2);}; obj.prototype.getName = function () { console.log(3);}; var getName = function () { console.log(4);}; function getName () { console.log(5);} obj.getName (); // ? getName (); // ? obj().getName (); // ? getName (); // ? new obj.getName (); // ? new obj().getName (); // ? new new obj().getName (); // ?
這三種數據的準備狀況咱們稱之爲「執行上下文」或者「執行上下文環境」。數組
做用域在函數定義時就已經肯定了。而不是在函數調用時肯定。閉包
var a = 10; function fn() { console.log(a); } function bar(f) { var a = 20; f() } bar(fn);
1 全局執行環境
2 fn執行環境
3 bar執行環境app
var a = 10; // 1 var b = 200; function fn() { var b = 20; function bar() { console.log(a + b); } bar(); // 3 } fn(); // 2
var a = 10; // 1 var b = 200; function fn() { var b = 20; function bar() { console.log(this.a + this.b); } bar(); // 3 } fn(); // 2
函數做爲返回值,函數做爲參數傳遞。函數
function fn () { var max = 10; return function bar(x) { if (x > max) { console.log(x); } } } var f1 = fn(); var max = 100; f1(15);