[英]How to extend a exist function in javascript
may this title of this question is duplicated , but I can't Google to find what I need. 可能这个问题的标题是重复的,但我不能谷歌找到我需要的东西。 For exam I have an js file created before, in this file I defined a function
为了考试我之前创建了一个js文件,在这个文件中我定义了一个函数
function fun1()
{
alert("a");
}
So I call this function in some "click" trigger 所以我在一些“点击”触发器中调用此函数
$("button").click(function(e){
fun1();
})
Now, I added new module and I don't want to change the define of function 1, I want to extend function 1 like this 现在,我添加了新模块,我不想更改函数1的定义,我想像这样扩展函数1
function fun1ex()
{
alert("b");
}
it mean that, when "button" clicked, 2 alert boxs will be shown ("a") and ("b") May I use class and prototype? 这意味着,当点击“按钮”时,将显示2个警告框(“a”)和(“b”)我可以使用类和原型吗? But I can't image how to do it.
但我无法想象如何做到这一点。 Thanks
谢谢
Just attach the new function to the click event: 只需将新功能附加到click事件:
$("button").click(function(e){
fun1();
});
$("button").click(function(e){
fun1ex();
});
This will alert("a")
and alert("b")
这将
alert("a")
和alert("b")
I think we can do something like that 我想我们可以做那样的事情
function mytest(text) {
this.text = text;
this.fun1 = function() {
alert("a "+text);
}
this.fun2 = function() {
alert("b "+text);
}
this.fun3 = function(){
for(var i in this) {
//executeFunctionByName("mytest."+i, window)
//eval("mytest."+i);
if(typeof this[i] === "function" && i != "fun3") {
this[i]();
}
//alert(typeof this[i]);
}
}
}
mytest.prototype.fun4 = function() {
alert("c " + this.text);
}
var test1 = new mytest("tung");
test1.fun3();
in this exam I defined fun3 to execute all methods avaiable in test1 object (except fun3) in another project (or js file) I can create new protopye function to extend fun3. 在这个考试中我定义了fun3来执行另一个项目(或js文件)中test1对象(fun3除外)中可用的所有方法我可以创建新的protopye函数来扩展fun3。
mytest.prototype.fun4 = function() {
alert("c " + this.text);
}
May be many people know this, but I hope it's useful for every newbies like me. 也许很多人都知道这一点,但我希望它对像我这样的每个新手都有用。 Thanks
谢谢
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.