作用域
作用域
- 对于作用域链, 我们可以可以通过创建态区定位快链条中的某一环
- 手动取消链条环甚至全局作用的时候,可以利用块级作用域做性能优化
- 函数和变量做作用域提升,变量优先,(函数依赖变量), 最后执行函数(先声明变量,在声明函数,函数将变量覆盖),注意: 赋值不会被提升,提升的永远是声明
console.log(a);
var a = 1;
var a = function () {
console.log("function");
};
if (true) {
var f = "123";
let e = "456";
}
console.log(f, e);
this 上下文 context 动态分析
函数直接调用
function foo() {
console.log(this);
}
foo();
隐式绑定 this 指向的是调用堆栈的上一级
function foo() {
console.log("隐式绑定", this);
}
const obj = {
a: 1,
foo,
};
obj.foo = foo;
obj.foo();
面试题
const obj = {
a: 1,
foo: function () {
console.log(this);
},
};
let foo1 = obj.foo;
foo1();
显式绑定 this (bind | apply | call)
- call 和 apply 的不同 ( call 参数依次传入,apply 参数通过数组传入 ), bind 返回值是个函数
- 手写 apply bind
Function.Prototype.myBind = function () {
const _this = this;
const args = Array.prototype.slice.call(arguments);
const newThis = args.shift();
return function () {
return _this.myApply(newThis, args);
};
};
Function.prototype.myApply = function (context) {
context = context || window;
context.fn = this;
let result = arguments[1] ? context.fn(...arguments) : context.fn();
delete context.fn;
return result;
};