javascript设计模式3this、call、apply
js中this总是指向一个对象,但是具体指向哪个对象是根据运行时基于函数的执行环境动态绑定的,而非函数被声明时的环境/
this的指向大致分为四种:
1.作为对象的方法调用
2.作为普通函数调用
3.构造器调用
4.Function.prototype.call 和 Function.prototype.apply调用
其中
1.作为对象的方法调用时,this指向该对象
var obj={ a:1, getA: function(){ alert( this === obj) alert( this.a ) } } obj.getA()
2.作为普通函数调用,总是指向全局对象,浏览器的js里,全局对象时window对象。
window.name = 'globalname'
var getName = function(){
return this.name;
}
console.log(getName()); // output: globalname
ECMAScript5的strict模式下,
function func(){
"use strict"
alert(this) // output: undefined
}
3.构造器调用
var myClass = function(){
this.name = "sven"
}
var obj = new myClass()
alert(obj.name) // output: sven
4.Funciton.prototype.call 或 Function.prototype.apply
与普通的函数调用相比,使用call和apply可以动态地改变传入函数的this
var obj1 = {
name : 'sven'
getName : function(){
return this.name
}
}
var obj2 = {
name: 'anne'
}
console.log( obj1.getName() ) // output : sven
console.log( obj2.getName.call(obj2) ) // output : anne
call和apply很好的体现了js的函数式语言特性,在js中,几乎每次编写函数式语言风格的代码,都离不开call和apply。
能够熟练运用这两个方法,是我们真正成为一名javascript程序员的重要一步。
call和apply的区别:
apply接受两个参数,第一个参数指定了函数体内this对象的指向。第二个参数为一个带小标的集合。
call传入的参数数量不固定,第一个参数也是代表函数体内的this指向,从第二个参数开始往后,每个参数被依次传入函数。
call和apply的用途:
改变this的指向;
Function.prototype.bind;
借助其他对象的方法。
Think Different, Make Different-编程是一个习惯

浙公网安备 33010602011771号