1

Is it possible to do something like this in Javascript:

var myFunction = function() {
    return true;
};

var anotherFunction = function () {
    return false;
};

$(function () {
    this.myFunction = anotherFunction;

    myFunction(); // to return false
});

Fiddle

My intuition says yes, but it doesn't work. How can I achieve this functionality?

1
  • One of those - it's getting late in the day stupidity things. Thanks for the help everyone. Commented Nov 29, 2013 at 15:17

3 Answers 3

2

It does work, you have just made a typo (missed off the this) that is causing the old function to be called;

$(function () {
    this.myFunction = anotherFunction;

    this.myFunction(); // to return false
});

or

$(function () {
    myFunction = anotherFunction;

    myFunction(); // to return false
});

In the context where you are overiding, this.myFunction and myFunction refer to different things.

Here is your fixed fiddle: http://jsfiddle.net/ExfP6/3/

Sign up to request clarification or add additional context in comments.

Comments

2

You can override any variable inside the outer scope with another variable with the same name:

var myFunction = function() {
    return true;
};

var anotherFunction = function () {
    return false;
};

$(function () {
    var myFunction = anotherFunction; // override the myFunction name inside this scope

    myFunction(); // returns false
});

myFunction(); // returns true

You can read more about scope here: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope

2 Comments

var myFunction = anotherFunction; // is it overriding or using new variable ?
@SHIN It is using a new variable that hides the one in the outer scope. As you can see in the outer scope myFunction() still returns true. Well i suppose you can argue that the code inside $() is executed after the call to myFunction() on the last line, but even if it was executed before, the myFunction in the outer scope would still be unaffected.
1

Works for me jsFiddle

var myFunction = function () {
    return true;
};

var anotherFunction = function () {
    return false;
};

$(function () {
    myFunction = anotherFunction; //remove this. your function was attach to a variable so by reassigning that variable with "anotherFunction" you will get the desired result.

    $('#result').html(""+myFunction());
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.