Skip to content

JS 主动指定 this 的值 #22

@hashdrinker

Description

@hashdrinker

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 {}

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions