关于this的值
let people = {
name: "zhangsan",
activities: ["bann","football","ping","bask"],
action: function() {
return this.activities.map(function (value) {
return ...
})
}
}
action
为people
对象中的一个方法,因此其中的this
的值为people
对象,可以使用this.activities
,但是action
方法中的匿名函数则不行,其this
指向的是window
全局
可以加以改变,使匿名函数中this
的值为people
对象
-
在
activities
方法中加入 语句const self = this;
,匿名函数可通过变量self
指向people
对象 -
箭头函数
return this.activities.map(value => { return ... })
apply & call & bind
都用来修改this
的值
function User(name) {
this.name = name;
}
let zzz = {sex: 'boy'};
User.call(zzz, 'zjh'); //this 的值为zzz, 'zjh'将作为参数传递给 name 变量
console.log(zzz);
apply
和call
的区别在于参数不同
function User(name, sex) {
....
}
User.call(zzz,'xm','boy');
User.apply(zzz, ['xm', 'boy']);
上面的两种调用方式结果相同,且都会立即执行,bind
不会立即执行,bind
返回一个函数