tungcan
tungcan

Reputation: 119

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

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

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? But I can't image how to do it. Thanks

Upvotes: 0

Views: 184

Answers (2)

tungcan
tungcan

Reputation: 119

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.

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

Upvotes: 1

Dalorzo
Dalorzo

Reputation: 20014

Just attach the new function to the click event:

$("button").click(function(e){
    fun1();
});

$("button").click(function(e){
    fun1ex();
});

This will alert("a") and alert("b")

Upvotes: 1

Related Questions