重写/隐藏Javascript函数

Overriding/hiding Javascript function

本文关键字:函数 Javascript 隐藏 重写      更新时间:2023-12-07

有可能在Javascript中做这样的事情吗:

var myFunction = function() {
    return true;
};
var anotherFunction = function () {
    return false;
};
$(function () {
    this.myFunction = anotherFunction;
    myFunction(); // to return false
});

Fiddle

我的直觉是肯定的,但它不起作用。如何实现此功能?

它确实有效,您只是犯了一个拼写错误(错过了this),导致调用旧函数;

$(function () {
    this.myFunction = anotherFunction;
    this.myFunction(); // to return false
});

$(function () {
    myFunction = anotherFunction;
    myFunction(); // to return false
});

在覆盖的上下文中,this.myFunctionmyFunction指的是不同的东西。

这是你固定的小提琴:http://jsfiddle.net/ExfP6/3/

您可以用另一个同名变量覆盖外部范围内的任何变量:

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

您可以在此处阅读有关范围的更多信息:https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope

适用于我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());
});