最近偶然感兴趣JavaScript里this的指向,来写一写我的认知!
bind() 绑定的含义
bind()方法会创建一个新的函数,为绑定函数,fun方法在this环境下调用
语句:
fun.bind(this,a1,a2,····)
第一个参数是this的指向
第二个参数开始是接收的参数列表。区别在于bind方法返回值是函数以及bind接收的参数列表的使用。
this.a = 1;
var module = {
a: 2,
getA: function () {
return this.a
}
}
module.getA()//2
//console.log(module.getA())
var getA1 = module.getA;
getA1();//1
//getA在外部调用,此时的this指向了全局对象
//console.log(getA1())
var getA2 = getA1.bind(module);
getA2();//2
//再把getA1方法绑定到module环境上
//console.log(getA2())
call()
语句:
function.call(this,[, a1[, a2[, …aN]]]);
调用一个对象的一个方法,用另一个对象替换当前对象
function Baby(name, age) {
this.name = name;
this.age = age;
}
function Child(n, a, w) {
// 调用Baby的call函数,并传递当前对象的实例this
Baby.call(this, n, a);
this.weight = w;
}
// 添加属于自己的方法
Child.prototype.eat = function (food) {
console.log(this.name + '喜欢吃' + food);
}
apply()
语句:
function.apply(thisObj[, argArray])
调用一个对象的一个方法,用另一个对象替换当前对象
var arr = [1,3,5,7,8,4,10]
var max = Math.max.apply(null,arr)//求数组中的最大项
alert(max)
今天呢,秧子就分享到这啦,感谢某大神的见解,接受批评和表扬!感谢阅读!!!