JS函数调用的四种方法:方法调用模式,函数调用模式,构造器调用模式,apply,call调用模式
1.方法调用模式:
先定义一个对象,然后在对象的属性中定义方法,通过myobject.property来执行方法,this即指当前的myobject
对象。
var blogInfo={
blogId:123,
blogName:"werwr",
showBlog:function(){alert(this.blogId)}
}
blogInfo.showBlog()
2.函数调用模式
定义一个函数,设置一个变量名保存函数,这时this指向到window对象。
var myfunc = function(a,b){
return a+b
}
alert(myfunc(3,4))
3.构造器调用模式
定义一个函数对象,在对象中定义属性,在其原型对象中定义方法。在使用prototype的方法时,必须实例化该对象才能调用其方法。
var myfunc = function(a){
this.a = a
}
myfunc.prototype = {
show:function(){alert(this.a)}
}
var newfunc = new myfunc("123123123")
newfunc.show()
4.apply,call调用模式
var myobject={}
var sum = function(a,b){
return a+b
}
var sum2 = sum.call(myobject,10,30)//var sum2 = sum.apply(myobject,[10,30])
alert(sum2)
用Function.prototype.bind即可比如this.ele.addEventListener('touchstart', this.selectmouse.bind(this))
定义在Dumplings.prototype里的函数如果作为Dumplings实例的方法调用,其this指针会指向Dumpling实例。
但作为参数传递给其他函数(比如addEventListener)时其this指针会被重置,由addEventListener控制。
你需要在prototype里的函数里调用其它同级的函数,this就应当指向Dumplings实例,用this.ele来绑定事件和访问事件的对象,这样才能通过this来访问其他同级对象。为防止addEventListener改变this的指向,需要用bind固定下来。