美文网首页
JS函数中的apply、call、bind理解

JS函数中的apply、call、bind理解

作者: 奋斗_登 | 来源:发表于2023-03-14 14:42 被阅读0次

函数有3个方法:apply()、call()、bind()。这3个方法都会以指定的this值来调用函数,即会设置调用函数时函数体内this对象的值。apply()方法接收两个参数:函数内this的值和一个参数数组。第二个参数可以是Array的实例,但也可以是arguments对象。参考以下例子。

window.color = 'red';
let o = {
    color: 'blue'
};

function productIntroduction(productName, price) {
    console.log(`This product name: ${productName}, ${price} yuan, ${this.color}`);
}
a
function applyProductIntroduction(productName, price) {
    productIntroduction.apply(this, arguments);
}

productIntroduction('fingerboard', 100); //This product name: fingerboard, 100 yuan, red

productIntroduction.apply(this, ['mouse', 88]); //This product name: mouse, 88 yuan, red
productIntroduction.apply(window, ['notebook', 6888]); //This product name: notebook, 6888 yuan, red
applyProductIntroduction('water cup', 48); //This product name: water cup, 48 yuan, red
productIntroduction.apply(o, ['iphone 14', 6500]); //This product name: iphone 14, 6500 yuan, blue

apply 的好处是可以将任意对象设置为任意函数的作用域,这样对象可以不用关心方法。
在使用productIntroduction.apply(o, ['iphone 14', 6500]); 把函数的执行上下文即this切换为对象o之后,结果就变成了显示"blue"了

call()方法与apply()的作用一样,只是传参的形式不同。第一个参数跟apply()一样,也是this值,而剩下的要传给被调用函数的参数则是逐个传递的。换句话说,通过call()向函数传参时,必须将参数一个一个地列出来

productIntroduction.call(o,'iphone 14', 6500); //This product name: iphone 14, 6500 yuan, blue

ECMAScript 5出于同样的目的定义了一个新方法:bind()。bind()方法会创建一个新的函数实例,其this值会被绑定到传给bind()的对象。比如:

let productBind = productIntroduction.bind(o, 'iphone 14', 6500);
console.info(typeof productBind) // function 
productBind() ////This product name: iphone 14, 6500 yuan, blue

可以看到productBind 的类型为function

相关文章

  • 简单分析apply、call、bind

    apply & call & bind 在 js中call/apply,都是为了改变函数运行的上下文(contex...

  • js中 call apply bind的理解

    js中的call apply bind都是用来改变this指向的 call apply bind都是用来改...

  • call apply

    js基础知识---call,apply,bind的用法 call,apply详解 javascript中,call...

  • this深入理解

    js中this指向有几种情况 全局环境 函数调用 构造调用 apply、call、bind绑定 箭头函数 全局环境...

  • call(),apply()和bind()

    call、apply和bind函数存在的区别:bind返回对应函数, 便于稍后调用; apply, call则是立...

  • apply, call, bind

    apply, call, bind 都是用来改变函数的this对象的指向 apply, call, bind 第一...

  • JS进阶知识点和常考面试题

    手写 call、apply 及 bind 函数 涉及面试题:call、apply 及 bind 函数内部实现是怎么...

  • bind call apply

    区别:call和apply调用就是执行函数 bind返回新函数 bind利用call或apply兼容i...

  • js小知识

    1. call、apply和bind的区别 call、apply和bind方法都是函数对象中的方法,用来动态地改变...

  • 前端面试题总结

    Function.prototype.bind实现 JS中的call、apply、bind方法thisObj的取值...

网友评论

      本文标题:JS函数中的apply、call、bind理解

      本文链接:https://www.haomeiwen.com/subject/zpyoldtx.html