非箭头函数:
如果是该函数是一个构造函数, this 指针指向一个新的对象
在严格模式下的函数调用下, this 指向 undefined
如果是该函数是一个对象的方法, 则它的 this 指针指向这个对象
箭头函数:
箭头函数不会创建自己的 this, 它只会从自己的作用域链的上一层继承 this
- let a,
- barObj = { msg: 'bar 的 this 指向' };
- fooObj = { msg: 'foo 的 this 指向' };
- function foo() {
- a(); // 结果:{ msg: 'bar 的 this 指向' }
- }
- function bar() {
- a = () => {
- console.log(this, 'this 指向定义的时候外层第一个普通函数'); //
- }; // 在 bar 输出当前 this 信息
- }
- bar.call(barObj); // 改变 bar 指向 barobj 执行后 a: 输出 this 的函数
- a()//(当前 a 输出 bar)
- foo.call(fooObj); // 将 foo 的 this 指向 fooObj,
- // bind: 绑定 this 不执行
- // call: 绑定 this 执行 n 参数任意类型
- // apply: 绑定 this 执行 第二个参数必须数组分解依次执行
- var person = {
- fullName: function(city, country) {
- return this.firstName + "" + this.lastName +","+ city +"," + country;
- }
- }
- var person1 = {
- firstName:"John",
- lastName: "Doe"
- }
- person.fullName.apply(person1, ["Oslo", "Norway"]);// 数组内传入前面函数的参数
- "John Doe,Oslo,Norway"
来源: http://www.bubuko.com/infodetail-3284689.html