Methods for calling JavaScript: 1. Method calling mode, this points to myobject at this time; 2. Function calling mode, this points to window at this time; 3. Constructor calling mode; 4. Apply calling mode.
The operating environment of this tutorial: Windows 7 system, JavaScript version 1.8.5, DELL G3 computer.
Method to call javascript:
1: Method calling mode
Please note that this points to myobject at this time.
/*方法调用模式*/ var myobject={ value:0, inc:function(){ alert(this.value) } } myobject.inc()
2: Function calling mode
Please note that this points to window
/*函数调用模式*/ var add=function(a,b){ alert(this)//this被绑顶到window return a+b; } var sum=add(3,4); alert(sum)
3: Constructor calling pattern
The book Essence of JavaScript Language recommends abandoning this method. Because there is a better way. Not introduced here. Will post it next time I blog.
A link will be added here.
/*构造器调用模式 摒弃*/ var quo=function(string){ this.status=string; } quo.prototype.get_status=function(){ return this.status; } var qq=new quo("aaa"); alert(qq.get_status());
4: apply calling mode
==We can look at a more useful apply instance. Look at the code at the bottom.
/*apply*/ //注意使用了上面的sum函数 //与myobject //这中调用方式的优点在于可以指向this指向的对象。 //apply的第一个参数就是this指针要指向的对象 var arr=[10,20]; var sum=add.apply(myobject,arr); alert(sum);
See the real application of this apply. bind This is a function that binds time
var bind=function(object,type,fn){ if(object.attachEvent){//IE浏览器 object.attachEvent("on"+type,(function(){ return function(event){ window.event.cancelBubble=true;//停止时间冒泡 object.attachEvent=[fn.apply(object)];//----这里我要讲的是这里 //在IE里用attachEvent添加一个时间绑定以后。 //this的指向不是到object对象本身所以。我们绑定的function里的this.id是无法正常工作的。 //但是如果我们用fn.apply(object) //这里可以看出我们是把apply的第一个对象也就是this的指向变更给了object所以this.id就变成了 //object.id 可以正常工作了。 } })(object),false); }else if(object.addEventListener){//其他浏览器 object.addEventListener(type,function(event){ event.stopPropagation();//停止时间冒泡 fn.apply(this) }); } } bind(document.getElementById("aaa"),"click",function(){alert(this.id)});
Related free learning recommendations: javascript video tutorial
The above is the detailed content of How to call javascript method. For more information, please follow other related articles on the PHP Chinese website!