如何将一个“对象”成JavaScript中的函数? [英] How to convert an "object" into a function in JavaScript?

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

问题描述

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

这是有效的:

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

此时, foo()调用该函数和 foo.baz 的值为qqqq。



但是,如果您执行属性分配第一部分,你如何随后将一个函数分配给变量?

  var bar = {baz:qqqq}; 

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

解决方案

在这里很容易混淆,但是你不能(根据我的理解容易或清楚地)做你想做的事。首先,Javascript中的每个对象都继承自Object对象。

  //这些做同样的事情
var foo = new Object();
var bar = {};

其次,Javascript中的函数 ARE 对象。具体来说,它们是一个Function对象。 Function对象从Object对象继承。签出函数构造函数

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

一旦你声明一个变量为Object,你就不能据我所知)将其转换为一个Function对象。你需要声明一个类型为Function的新对象(使用函数构造函数,赋值变量为匿名函数等),然后复制旧对象的方法属性。



最后,预测一个可能的问题,即使某种东西被声明为一个函数,你也不能(据我所知)改变函数体/源。

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"?

This works:

var foo = function() { return 1; };
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" };

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.

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

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

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(){};

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.

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天全站免登陆