Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JS 主动指定 this 的值 #22

Open
rhymecoding opened this issue Aug 29, 2018 · 0 comments
Open

JS 主动指定 this 的值 #22

rhymecoding opened this issue Aug 29, 2018 · 0 comments
Labels

Comments

@rhymecoding
Copy link

this 的值是在预编译阶段指定的,通过下面 3 个方法,开发者可以主动指定 this 的值。

  • function.call(thisArg, arg1, arg2, ...)
  • function.apply(thisArg, [argsArray])
  • fun.bind(thisArg[, arg1[, arg2[, ...]]])

call/apply 无需介绍,这里仅介绍 bind 方法。

bind

返回一个绑定了 this 的新函数,后面的参数会在实参之前传递给新函数

function fun () {
  console.log(arguments, this);
}

var thisArg = {
  name: 'thisArg'
}

var newFun = fun.bind(thisArg, 0, 1);

newFun(2); // { '0': 0, '1': 1, '2': 2 } { name: 'thisArg' }

bind 绑定的 this 的优先级比 call/apply 高

function fun () {
  console.log(arguments, this);
}

var thisArg = {
  name: 'thisArg'
}

var newFun = fun.bind(thisArg, 0, 1);

newFun(2); // { '0': 0, '1': 1, '2': 2 } { name: 'thisArg' }

var thisArgNew = {
  name: 'thisArgNew'
}

newFun.call(thisArgNew, 2); // { '0': 0, '1': 1, '2': 2 } { name: 'thisArg' }

当使用 new 操作新函数时,bind 绑定的 this 失效

function fun () {
  console.log(arguments, this);
}

var thisArg = {
  name: 'thisArg'
}

var newFun = fun.bind(thisArg, 0, 1);

newFun(2); // { '0': 0, '1': 1, '2': 2 } { name: 'thisArg' }

new newFun(2); // { '0': 0, '1': 1, '2': 2 } fun {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

2 participants