this的理解
this是JavaScript语言的一个关键字,随着函数的不同使场合,this的指向会发生变换,但始终不变的是this永远指向调用函数的那个对象
function f1(){ this.a=1; console.log(this.a) } f1()
证明this指向 为全局对象
var a=0; function f2(){ this.a=10; } f2(); console.log(a)//0 /* *函数内部的变量前如果没有加var 关键字,变量就会被提前到作用域的顶部(声明提前),成为全局对象 *此时a=0的值被this.a=10覆盖 */
当函数作为对象的方法调用时,this指向这个 上级对象。
var obj={ name: 'swatch17', age: 23, f3: function(){ console.log(this.name) } } obj.f3() /*此时this指向obj*/
当作为构造函数调用时,this指向这个新的对象
function f4(){ this.a=6; } var four=new f4() f4();//此时的this指向全局; console.log(four.a)//此时的this指向four;
apply与call
- call()方法接受的是若干个参数的列表,而apply()方法接受的是一个包含多个参数的数组
- call() 方法在使用一个指定的this值和若干个指定的参数值的前提下调用某个函数或方法.Function.prototype.call();
apply与call都属于Function.prototype的方法;两者都是为了改变函数运行的上下文,即函数内部this的指向
function team(){} team.prototype={ club : 'Livepool', say:function(){console.log('My home team is ' + this.club );} } var fansA=new team; fansA.say()//My home team is Liverpool //通过apply与call改变this的指向 fansB = {club:'Chelsea'} fansA.say.apply(fansB)//My home team is Chelsea fansA.say.call(fansB)//My home team is Chelsea /*此时this指向fansB*/
当apply()、call()的参数为空时,默认调用全局对象
参考:
MDN