newPromise / js-

0 stars 0 forks source link

函数声明提升, bind #28

Open newPromise opened 6 years ago

newPromise commented 6 years ago

使用函数声明提示的时候,函数声明会被提升到声明时所在作用域的最顶部

function foo () {
  console.log(a);// undefined
  return; // 即使存在 return 语句也不会改变结果
  var a = 2; 赋值语句位置不变,声明 `var a` 被提升到了函数作用域的最顶部
}

注意对于函数声明表达式是不能进行函数声明提升的:

bax();  // error  bax is not a function 
var bax = function () {
  console.log('yes');
}
bax(); // 'yes'

声明提升发生在编译阶段,而不是运行阶段,因此,下面这段代码就好理解了:

var foo = 1
function bax () {
  foo = 10;
  return;
  function foo () {};
}
bax();
alert(foo);

这里面,在函数 bax 内部会进行声明提升, 函数声明 function foo () {} 会被提升到 bax 函数的最顶端,这里 foo = 10, 寻找到的标识符是被定义的函数 foo,而不是全局变量 var foo = 1;

newPromise commented 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) ;  //  ‘张宁宁’
newPromise commented 6 years ago
使用 call apply bind 的区别

使用 call bind 以及 apply 的目的都是为了改变函数中的 this 指向值 call 以及 apply 的作用是函数即调即用 对于 bind 而言, 使用 bind 生成的是一个被改造过的函数

newPromise commented 6 years ago

示例如下

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);
  }
}