Open newPromise opened 6 years ago
使用 Function.propertype.bind() 的目的在于进行函数绑定
func.bind(obj) 使用 bind
语法的时候, func 中的 this 值会指向 obj 对象:
var foo = {
name: '张宁宁',
getName: function () {
return this.name;
}
}
let name = foo.getName();
name // undefined 因为这时候 this 指向的是全局 `window` 对象,因此不存在的
解决办法:
// 使用 bind 解决的隐性丢失绑定问题
let name = foo.getName.bind(foo);
console.log(name) ; // ‘张宁宁’
call
apply
bind
的区别使用 call bind 以及 apply 的目的都是为了改变函数中的 this
指向值
call 以及 apply 的作用是函数即调即用
对于 bind
而言, 使用 bind 生成的是一个被改造过的函数
function foo (a, b) {
console.log(this.x, a, b);
}
let obj = {x: 1};
let new_fn = foo.bind(obj, 2);
new_fn(); // 1,2, undefined
// 需要将新生成的函数保存到一个变量中去
// 可以进行持续传入参数,
new_fn(3); // 1, 2, 3
如何实现 bind 方法在不同浏览器下的兼容性问题:
Function.property.bind = Function.property.bind || function (context) {
var that = this;
return function () {
return that,apply(context, arguments);
}
}
使用函数声明提示的时候,函数声明会被提升到声明时所在作用域的最顶部
注意对于函数声明表达式是不能进行函数声明提升的:
声明提升发生在编译阶段,而不是运行阶段,因此,下面这段代码就好理解了:
这里面,在函数
bax
内部会进行声明提升, 函数声明function foo () {}
会被提升到bax
函数的最顶端,这里foo = 10
, 寻找到的标识符是被定义的函数foo
,而不是全局变量var foo = 1
;