本文继续讨论 this 指向 问题,今天讨论:
函数中的this
0 1
箭头函数
箭头函数忽略任何形式的this指向改变.
示例1:
'use strict'
const test = ()=> {
console.log(this);
}
const test2 = function () {
console.log(this);
}
test();
test2();
结果为:
window
undefined
松散模式下,test与test2执行打印结果都为window. 当在严格模式下,test打印还是为window, test2 则打印undefined
箭头函数中的this ,不是谁调用就指向谁
示例2:
obj.test=()=>{
console.log(this);
}
obj.test();
结果为:window
示例3:
obj.test=function(){
var t1 = ()=>{
var t2=()=>{
console.log(this);
}
t2();
}
t1();
}
obj.test();
结果为:obj (t1, t2 都为箭头函数)
示例4:
obj.test=function(){
var t1 = function{
var t2=()=>{
console.log(this);
}
t2();
}
t1();
}
obj.test();
结果为:window
总结:箭头函数 this 作用域, 指向外层非箭头函数作用域的this
另注:
箭头函数一定不能是一个构造器.
如下:new test(); 将会报错
var test = ()=>{
console.log('test 箭头函数');
}
var test2 =function (){
console.log('test 普通函数');
}
运行结果:
0 2
call、apply、bind 改变this
call
call() 方法使用一个指定的 this 值和单独给出的一个或多个参数来调用一个函数。
apply
apply() 方法调用一个具有给定this值的函数,以及以一个数组(或类数组对象)的形式提供的参数。
bind
bind() 方法创建一个新的函数,在 bind() 被调用时,这个新函数的 this 被指定为 bind() 的第一个参数,而其余参数将作为新函数的参数,供调用时使用。
总结:
call、apply、bind 三个方法都可以改变函数中this 的指向
call、apply :立即执行
bind 返回一个新函数
var obj={
name:'sunshine',
sayHi:function () {
console.log(this.name);
}
}
var obj2 = {name:'Double yong'}
改变this
obj.sayHi.call(obj2);
obj.sayHi.apply(obj2);
上面的代码,将立即调用函数,且打印obj2.name中的name属性。
结果为:
Double Yong
Double yong
var fn = obj.sayHi.bind(obj2);
fn();
bind()函数返回会的一个新的函数 ,所以去调用
call,apply 的区别,在于如果有参数,参数传递的方式不同
如下:
function Product(name, price) {
this.name = name;
this.price = price;
}
function Food(name, price) {
Product.call(this, name, price);
// Product.apply(this, [name, price]);
// 或Product.apply(this, arguments);
this.category = 'food';
}