声明后你能改变一个Javascript函数吗? [英] Can you alter a Javascript function after declaring it?

查看:89
本文介绍了声明后你能改变一个Javascript函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有 var a = function(){return 1; } 。是否可以改变 a ,以便 a()返回 2 ?也许通过编辑 a 对象的属性,因为每一个函数都是一个对象



更新:哇,谢谢所有回复。但是,恐怕我并不想简单地重新分配变量,而是实际编辑现有函数。我正在考虑如何结合部分功能在Scala中创建一个新的 PartialFunction 。我有兴趣在Javascript中编写类似的东西,并认为现有的函数可能会更新,而不是创建一个全新的 Function 对象。

$ b $你可以用JavaScript来做各种有趣的事情,包括重新定义函数:

pre

> var a = function(){return 1; }

alert(a()); // 1

//保留一个引用
var old = a;

//重新定义
a = function(){
//用指定的参数调用原始函数,存储结果
var originalResult = old.apply(old ,参数);
//添加一个
return originalResult + 1;
};
alert(a()); // 2

Voila。

编辑:已更新以在疯狂的场景中显示此内容:

  var test = new String(123); 
console.log(test.toString()); // log 123
console.log(test.substring(0)); //日志123
String.prototype.substring = function(){returnhahanope; }
console.log(test.substring(0)); // logs haha​​nope

你可以在这里看到,即使test是先定义的,然后我们重新定义substring()之后,更改仍然适用。



注意:如果你这样做,你真的应该重新考虑你的架构...你会混淆当他/她正在查看一个应该返回1的函数定义时,5年后,一些可怜的开发人员开始废话......但是似乎总是返回2 ....


Let's say I have var a = function() { return 1; }. Is it possible to alter a so that a() returns 2? Perhaps by editing a property of the a object, since every function is an object?

Update: Wow, thanks for all the responses. However, I'm afraid I wasn't looking to simply reassign a variable but actually edit an existing function. I am thinking along the lines of how you can combine partial functions in Scala to create a new PartialFunction. I am interested in writing something similar in Javascript and was thinking that the existing function could perhaps be updated, rather than creating an entirely new Function object.

解决方案

You can do all kinds of fun stuff with javascript, including redefining functions:

var a = function(){ return 1; }

alert(a()); //1

// keep a reference
var old = a;

// redefine
a = function(){
  // call the original function with any arguments specified, storing the result
  var originalResult = old.apply(old, arguments);
  // add one
  return originalResult + 1;
};
alert(a()); //2

Voila.

Edit: Updated to show this in a crazier scenario:

var test = new String("123");
console.log(test.toString()); // logs 123
console.log(test.substring(0)); // logs 123
String.prototype.substring = function(){ return "hahanope"; }
console.log(test.substring(0)); // logs hahanope

You can see here that even though "test" is defined first, and we redefine substring() afterwards, the change still applies.

Side note: you really should reconsider your architecture if you're doing this...you're going to confuse the crap out of some poor developer 5 years down the road when s/he's looking at a function definition that's supposed to return 1, but seems to always return 2....

这篇关于声明后你能改变一个Javascript函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆