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

JavaScript模拟实现call、apply、bind #14

Open
GGXXMM opened this issue Aug 8, 2019 · 0 comments
Open

JavaScript模拟实现call、apply、bind #14

GGXXMM opened this issue Aug 8, 2019 · 0 comments
Labels
⭐️ js js knowledge

Comments

@GGXXMM
Copy link
Owner

GGXXMM commented Aug 8, 2019

语法

  • call
fun.call(thisArg, arg1, arg2, ...)

调用一个函数, 其具有一个指定的this值和分别地提供的参数(参数的列表)。

  • apply
func.apply(thisArg, [argsArray])

调用一个函数,以及作为一个数组(或类似数组对象)提供的参数。

call、apply、bind的功能

1、call、apply、bind都是用来改变函数的this指向,第一个参数都是this要指向的新对象。
2、call、apply类似,都是立即调用函数,但第二个参数后续传参格式不同,call后续传参是 ,隔开,apply第二个参数是数组格式。
3、bind是返回对应的函数,便于后续调用。

模拟call、apply、bind

模拟call()

Function.prototype.newCall = function(context = window, ...args) {
  context.fn = this;

  let result = context.fn(...args);
  delete context.fn;
  return result;
}
let foo = {
    value: 1
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.newCall(foo, 'black', '18') // black 18 1

模拟apply()

Function.prototype.newApply = function(context = window, argArr){
  context.fn = this;

  let result = context.fn(...argArr);
  delete context.fn;
  return result;
}
function bar(name, age) {
    console.log(name)
    console.log(age)
    console.log(this.value);
}
bar.newApply(foo, ['black', 18]) // black 18 1

模拟bind()

Function.prototype.newBind = function(context = window, ...args) {
  if (typeof this !== "function") {
    throw new Error("this must be a function");
  }
  context.fn = this;

  return function(..._args) {
    args = args.concat(_args);
    context.fn(...args);
    delete context.fn;
  }
}
@GGXXMM GGXXMM added the ⭐️ js js knowledge label Dec 7, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
⭐️ js js knowledge
Projects
None yet
Development

No branches or pull requests

1 participant