call apply的区别
function.prototype.call
格式 fx.call(thisObj,arg1,arg2,...);
call传参数个数不限,第一个参数表示调用函数的f(x)体内this的指向,从第二个参数开始一次后依次传入函数
var age = 40;
var xiaoMing = {
age:30
};
var xiaoLi = {
age:20
};
var getAge = function(){
console.log(this.age)
};
getAge.call(xiaoMing);//30
getAge.call(xiaoLi)//20
getAge.call(undefined);//40
getAge.call(null)//40
getAge() //40
如果传入fx.call()的第一个参数为null,那么表示函数fx体内this指向宿主对象,在浏览器中是window对象 在这可以认为fx()==fx.call(null)==fx.call(undefined) 注意:严格模式下this指向null
var getAge = function(){
'use strict'
console.log(this.age)
}
理解this的应用
this位于对象方法内,此时指向该对象
var name = 'window';
var Student = {
name: 'kobe',
getName: function(){
console.log(this == Student);
//true
console.log(this.name) //true
}
}
Student.getName();
this位于一个普通函数内,this指向全局
var name = 'window';
var Student = function(){
var name = 'kobe';
return this.name//window
}
this使用在构造函数(构造器里面),表示this指向的那个返回的对象
var name = 'window';
var Student = function(){
this.name = 'student'
}
var s1 = new Student();
console.log(s1.name)//student
**注意:**如果构造器返回的也是一个Object对象,这时候this指向的这个Object
var name = 'window';
var Student = function(){
this.name = 'student';
this.age = 12;
return {
name:'botStudent';
}
}
var s1 = new Student();
console.log(s1)//输出Student的返回值{name:'boyStudent'}
console.log(s1.name)//boyStudent
console.log(s1.age)//undefined
this指向失效的问题
var name = 'window';
var Student = {
name: 'kobe',
getName: function () {
console.log(this)//指向Student
console.log(this.name)
}
}
Student.getName();//kobe
var s1 = Student.getName;//
s1();//this指向了window