重写/隐藏Javascript函数
Overriding/hiding Javascript function
有可能在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.myFunction
和myFunction
指的是不同的东西。
这是你固定的小提琴: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());
});
相关文章:
- 从函数JavaScript返回不可变数组/对象
- 将对象传递给函数.JavaScript
- 如何定义const函数javascript(语法糖)
- 新的日期函数javascript
- TypeError:this.getAttribute不是一个函数-javascript
- 从函数javascript发送变量
- 扩展自容器函数Javascript
- 从内部函数javascript内部分配外部函数的对象
- 使用函数JavaScript中的函数
- 在这里使用回调函数(JavaScript)有什么好处吗
- 来自函数 Javascript 的 NaN 返回值 ||函数执行顺序
- 将“e”传递给一个新函数 - javascript
- 调用函数中的一个函数——Javascript
- 传递的变量不适用于我的函数-Javascript
- 如何将类方法设置为等于多个函数?-Javascript
- 显示php中的函数javascript
- 如何使用php代码创建函数Javascript弹出框
- 未调用的外部函数-javascript
- 如何在类中运行函数.Javascript
- 关闭mouseover上的一个函数——Javascript,jQuery