this和call、apply、bind
this---------------属性或方法“当前”所在的对象
不同位置的this指向:
//1.函数中包含多层: var o = { f1: function () { console.log(this); var f2 = function () { console.log(this); }(); } } o.f1() // Object // Window //2.数组处理方法中的this: var o = { v: 'hello', p: [ 'a1', 'a2' ], f: function f() { this.p.forEach(function (item) { console.log(this.v + ' ' + item); }); } } o.f() // undefined a1 // undefined a2 //3.回调函数中的this: var o = new Object(); o.f = function () { console.log(this === o); } // jQuery 的写法 $('#button').on('click', o.f);
绑定this的方法:
1.使用中间变量固定this
var o = { v: 'hello', p: [ 'a1', 'a2' ], f: function f() { var that = this; this.p.forEach(function (item) { console.log(that.v+' '+item); }); } } o.f() // hello a1 // hello a2
2.call:指定函数内部this的指向(即函数执行时所在的作用域),然后在所指定的作用域中,调用该函数。
参数:
第一个参数就是this所要指向的那个对象,后面的参数则是函数调用时所需的参数。
如果参数为空、null和undefined,则默认传入全局对象。
3.apply:指定函数内部this的指向(即函数执行时所在的作用域),然后在所指定的作用域中,调用该函数。
参数:
第一个参数也是this所要指向的那个对象,如果设为null或undefined,则等同于指定全局对象。
第二个参数则是一个数组,该数组的所有成员依次作为参数,传入原函数。原函数的参数,在call方法中必须一个个添加,但是在apply方法中,必须以数组形式添加。
4.bind:将函数体内的this绑定到某个对象,然后返回一个新函数。
参数:所要绑定this的对象。
用法:
//call var obj = {}; var f = function () { return this; }; f() === window // true f.call(obj) === obj // true //apply function f(x, y){ console.log(x + y); } f.call(null, 1, 1) // 2 f.apply(null, [1, 1]) // 2 //bind var d = new Date(); d.getTime() // 1481869925657 var print = d.getTime; print() // Uncaught TypeError: this is not a Date object. var print = d.getTime.bind(d); print() // 1481869925657
参考:
https://wangdoc.com/javascript/oop/this
https://blog.csdn.net/qq_43000315/article/details/125360096

浙公网安备 33010602011771号