JavaScript重定义this指向(apply、call、bind)
一、apply()在JavaScript中apply()是函数的原型方法Function.prototype.apply用于调用一个函数并显式指定该函数内部的this值同时以数组或类数组对象的形式传入参数。基本语法func.apply(thisArg,[argsArray]);func要调用的函数。thisArg在函数执行时绑定到this的对象。如果传null或undefined在非严格模式下this指向全局对象浏览器中是windowNode.js 中是global严格模式下为null。[argsArray]一个数组或类数组对象如arguments、NodeList其元素将作为参数依次传给函数。如果不需要传参可传[]或null/undefined。返回值被调用函数的返回值。核心作用改变函数内部的this指向。以数组形式传递参数。经典示例借用数组方法最常见用途。// 类数组对象有length和索引但不是Array。constarrayLike{0:a,1:b,2:c,length:3};// 借用Array.prototype.slice方法。constrealArrayArray.prototype.slice.apply(arrayLike);console.log(realArray);// [a, b, c]。现代写法可用Array.from(arrayLike)但apply在旧代码中很常见。求最大值/最小值配合Math。constnumbers[5,6,2,8,1];// Math.max接收多个参数不接受数组。// Math.max(numbers) → NaN。// 使用apply展开数组。constmaxMath.max.apply(null,numbers);constminMath.min.apply(null,numbers);console.log(max);// 8。console.log(min);// 1。ES6可用扩展运算符替代Math.max(...numbers)。改变this上下文。constperson{name:Alice};functiongreet(greeting,punctuation){return${greeting},${this.name}${punctuation};}// 使用apply调用greet指定this为person参数以数组传入。constresultgreet.apply(person,[Hello,!]);console.log(result);// Hello, Alice!。继承中调用父类构造函数ES5写法。functionAnimal(name){this.namename;}functionDog(name,breed){// 调用父类构造函数绑定this到当前实例。Animal.apply(this,[name]);this.breedbreed;}constdognewDog(Buddy,Golden Retriever);console.log(dog.name);// Buddy。console.log(dog.breed);// Golden Retriever。ES6可用super(name)替代。applyvscallvsbind方法参数形式是否立即执行返回值func.apply(thisArg, [arg1, arg2, ...])数组/类数组是函数执行结果func.call(thisArg, arg1, arg2, ...)逐个列出是函数执行结果func.bind(thisArg, arg1, arg2, ...)逐个列出可部分预设否新函数绑定后的greet.apply(person,[Hi,.]);// Hi, Alice.。greet.call(person,Hi,.);// Hi, Alice.。constboundGreetgreet.bind(person,Hi);boundGreet(.);// Hi, Alice.。二、call()在JavaScript中call()是函数的原型方法Function.prototype.call用于立即调用一个函数并显式指定该函数内部的this值同时以逐个参数的形式传入参数。它和apply()非常相似核心区别只在于参数的传递方式。基本语法func.call(thisArg,arg1,arg2,...,argN);func要调用的函数。thisArg函数执行时绑定到this的对象。若为null或undefined非严格模式 →this指向全局对象浏览器中是window。严格模式 →this就是null。arg1, arg2, ...逐个列出的参数不是数组。返回值被调用函数的返回值。核心作用改变函数内部的this指向。以“展开”的形式传参与apply的数组形式相对。经典示例借用其他对象的方法。constobj1{name:Alice,greet:function(greeting){return${greeting}, Im${this.name};}};constobj2{name:Bob};// 让 obj1.greet 在obj2的上下文中执行。constresultobj1.greet.call(obj2,Hello);console.log(result);// Hello, Im Bob。这里this指向了obj2所以this.name是Bob。将类数组转为真数组配合Array.prototype.slice。functiondemo(){// arguments是类数组。constargsArrayArray.prototype.slice.call(arguments);console.log(argsArray);// [1, 2, 3]。}demo(1,2,3);现代写法Array.from(arguments)或[...arguments]但需注意arguments不是真正的可迭代对象在某些环境下需谨慎。检查数据类型利用Object.prototype.toString。functiongetType(value){returnObject.prototype.toString.call(value).slice(8,-1);/* 若不加“.slice(8, -1)”进行切分输出结果如下 [object Array] [object Date] [object Null] */}console.log(getType([]));// Array。console.log(getType(newDate()));// Date。console.log(getType(null));// Null。这是判断JS数据类型的最可靠方法之一因为call能确保toString在目标值上正确执行。继承ES5写法。functionAnimal(name){this.namename;}functionDog(name,breed){// 调用父构造函数绑定this到当前实例。Animal.call(this,name);this.breedbreed;}constdognewDog(Max,Labrador);console.log(dog.name);// Max。console.log(dog.breed);// Labrador。ES6可用classsuper()替代。callvsapplyvsbind方法参数形式是否立即执行返回值func.call(thisArg, arg1, arg2, ...)逐个参数是函数执行结果func.apply(thisArg, [argsArray])数组/类数组是函数执行结果func.bind(thisArg, arg1, arg2, ...)逐个参数可预设否新函数functiongreet(a,b){return${a}${this.name}${b};}constperson{name:Tom};greet.call(person,Hi,!);// Hi Tom !。greet.apply(person,[Hi,!]);// Hi Tom !。constboundgreet.bind(person,Hi);bound(!);// Hi Tom !。三、bind()在JavaScript中bind()是函数的原型方法Function.prototype.bind用于创建一个新函数绑定函数该新函数在被调用时永久绑定指定的this值。可预设部分参数称为“柯里化”或“部分应用”。bind()不会立即执行原函数而是返回一个绑定了上下文和参数的新函数。基本语法constnewFuncfunc.bind(thisArg,arg1,arg2,...);func原始函数。thisArg新函数执行时内部this指向的对象。arg1, arg2, ...可选预设的参数会填充到新函数参数的前面。返回值一个全新的函数。核心特性永久绑定this不可再被call/apply覆盖。constperson{name:Alice};functiongreet(){returnHello,${this.name};}constboundGreetgreet.bind(person);console.log(boundGreet());// Hello, Alice。// 即使用call/apply也无法改变this。console.log(boundGreet.call({name:Bob}));// 仍然是Hello, Alice一旦用bind绑定this就永久固定了。支持预设参数部分应用 / 柯里化。functionmultiply(a,b){returna*b;}// 预设第一个参数为 2constdoublemultiply.bind(null,2);console.log(double(5));// 10 (2 * 5)console.log(double(10));// 20 (2 * 10)也可以预设多个参数functionadd(a,b,c){returnabc;}constaddFiveAndTenadd.bind(null,5,10);console.log(addFiveAndTen(3));// 18 (5 10 3)经典使用场景解决回调函数中this丢失问题。classTimer{constructor(){this.seconds0;}start(){// 问题setTimeout 中的回调函数this指向window非严格模式。// setTimeout(function() {// this.seconds; // 报错或无效。// }, 1000);// 解决方案用bind绑定this。setTimeout(function(){this.seconds;console.log(this.seconds);}.bind(this),1000);}}consttimernewTimer();timer.start();// 正常输出1。现代写法更推荐用箭头函数自动继承外层thissetTimeout((){this.seconds;},1000);事件监听器中保持上下文。classButton{constructor(element){this.elementelement;this.clickCount0;// 绑定this确保handleClick中的this指向当前实例。this.element.addEventListener(click,this.handleClick.bind(this));}handleClick(){this.clickCount;console.log(Clicked${this.clickCount}times);}}若不用bindhandleClick被调用时this会指向elementDOM元素导致错误。创建专用函数函数工厂functionlog(level,message){console.log([${level}]${message});}consterrorLoglog.bind(null,ERROR);constinfoLoglog.bind(null,INFO);errorLog(Something went wrong);// [ERROR] Something went wronginfoLog(Process started);// [INFO] Process startedbindvscallvsapply方法是否立即执行参数形式主要用途func.bind(thisArg, ...args)否逐个参数创建绑定后的新函数用于回调、事件等。func.call(thisArg, arg1, arg2, ...)是逐个参数立即调用临时指定this。func.apply(thisArg, [args])是数组立即调用参数以数组传入。注意事项bind返回的是新函数原函数不变。多次bind只有第一次生效constffunction(){returnthis.value;};constgf.bind({value:1});consthg.bind({value:2});console.log(h());// 1不是 2绑定函数的length属性会变化functionfn(a,b,c){}console.log(fn.length);// 3。console.log(fn.bind(null,1).length);// 2已预设1个参数。对bind返回的新函数使用new关键字创建实例letfoo{value:1,};functionPerson(name,age){this.namename;this.ageage;console.log(this.name);console.log(this.age);console.log(this.value);}Person.prototype.getNamefunction(){returnthis.name;};letPerPerson.bind(foo,xiaoming);Per(18);// 输出xiaoming 18 1。console.log(foo.name);// 输出xiaoming。console.log(foo.age);// 输出18。console.log(foo.value);// 输出1。letpernewPer(18);// 输出xiaoming 18 undefined。console.log(per.getName());// 输出xiaoming。console.log(foo.name);// 输出xiaoming。console.log(foo.age);// 输出18。console.log(foo.value);// 输出1。// 由上述结果可知对bind方法返回的绑定对象的函数使用new关键字创建实例时原绑定的对象在创建的实例中会失效。
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2410678.html
如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!