如何转换“对象"到 JavaScript 中的函数? [英] How to convert an "object" into a function in JavaScript?

查看:14
本文介绍了如何转换“对象"到 JavaScript 中的函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

JavaScript 允许将函数视为对象——如果您首先将变量定义为函数,则随后可以向该函数添加属性.你如何做相反的事情,并为对象"添加一个函数?

JavaScript allows functions to be treated as objects--if you first define a variable as a function, you can subsequently add properties to that function. How do you do the reverse, and add a function to an "object"?

这有效:

var foo = function() { return 1; };
foo.baz = "qqqq";

此时foo()调用了函数,foo.baz的值为qqqq".

At this point, foo() calls the function, and foo.baz has the value "qqqq".

但是,如果您先进行属性分配部分,那么后续如何将函数分配给变量?

However, if you do the property assignment part first, how do you subsequently assign a function to the variable?

var bar = { baz: "qqqq" };

我现在可以做些什么来安排bar.baz具有值qqqq" bar()来调用函数?

What can I do now to arrange for bar.baz to have the value "qqqq" and bar() to call the function?

推荐答案

这里很容易混淆,但您不能(轻松地或清楚地或据我所知)做您想做的事.希望这将有助于解决问题.

It's easy to be confused here, but you can't (easily or clearly or as far as I know) do what you want. Hopefully this will help clear things up.

首先,Javascript 中的每个对象都继承自 Object 对象.

First, every object in Javascript inherits from the Object object.

//these do the same thing
var foo = new Object();
var bar = {};

其次,Javascript中的函数ARE对象.具体来说,它们是一个 Function 对象.Function 对象继承自 Object 对象.查看函数构造函数

Second, functions ARE objects in Javascript. Specifically, they're a Function object. The Function object inherits from the Object object. Checkout the Function constructor

var foo = new Function();
var bar = function(){};
function baz(){};

一旦你将一个变量声明为一个对象",你就不能(容易地或清楚地或据我所知)将它转换为函数对象.您需要声明一个 Function 类型的新对象(带有函数构造函数、为变量分配匿名函数等),并从旧对象中复制方法的任何属性.

Once you declare a variable to be an "Object" you can't (easily or clearly or as far as I know) convert it to a Function object. You'd need to declare a new Object of type Function (with the function constructor, assigning a variable an anonymous function etc.), and copy over any properties of methods from your old object.

最后,预测一个可能的问题,即使将某些内容声明为函数,您也不能(据我所知)更改 functionBody/源.

Finally, anticipating a possible question, even once something is declared as a function, you can't (as far as I know) change the functionBody/source.

这篇关于如何转换“对象"到 JavaScript 中的函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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