草庐IT

javascript - 同时是一个函数和一个对象?

coder 2024-07-15 原文

是否有可能在创建一个函数变量之后,您实际上可以为它分配属性,就好像它是一个普通对象一样?这就是我所做的:

var example = function(a, b){
    console.log(a, b);
}
example.someProperty = 'hi there';

然后我在浏览器控制台中输入了这些行:

example('Hello', 'world') // Hello world
example.someProperty // hi there

所以现在“示例”var 基本上同时充当函数和对象。这对我提出了一些问题,其中一个是为什么,另一个是有没有办法通过创建对象字面量来做到这一点,因为我想不出这样的方法。

最佳答案

So now basically the 'example' var acts as a function and as an object at the same time.

它不充当一个函数和一个对象,它一个函数和一个对象。函数是 JavaScript 中的对象。

This raised some questions for me, one of which is why

从根本上说,因为那是 Eich 在 1995 年 5 月的那 10 天里决定做的事情。为什么他决定这样做只有他能回答,但多年来有许多语言也认为没有理由将函数视为特殊的东西和不同的。想必他也受到了这些影响。函数是合适的对象是非常方便和灵活的。例如:

function foo() {
    // ...
}
var f = foo;

我可以使用变量 f 来引用 foo 因为 foo 是一个对象。在许多语言中,例如 Java,这样做真的很痛苦(尽管 Java 现在好一些,这要归功于其最近添加的 lambda)。

由于函数是对象,它们有原型(prototype),这意味着我可以向所有 函数添加功能。例如:我发现能够接受一个函数并“融入”(或“curry”)参数非常方便:

// A simple function
function foo(a, b) {
    console.log("a is " + a);
    console.log("b is " + b);
}

// Create a new one that, when called, will call the original passing in
// 1 as the first argument and then passing in any further arguments,
// preserving the `this` it was called with
var f = foo.curry(1);

// Call it
f(2); // "a is 1" / "b is 2"

由于 JavaScript 没有 curry 函数(它有 bind,这很相似,但会干扰 this),我可以加一个:

var slice = Array.prototype.slice;
Object.defineProperty(Function.prototype, "curry", {
    value: function() {
        var f = this;
        var args = slice.call(arguments);
        return function() {
            return f.apply(this, args.concat(slice.call(arguments)));
        };
    }
});

瞧,现在我可以在任何函数上使用 curry:

var slice = Array.prototype.slice;
Object.defineProperty(Function.prototype, "curry", {
  value: function() {
    var f = this;
    var args = slice.call(arguments);
    return function() {
      return f.apply(this, args.concat(slice.call(arguments)));
    };
  }
});

// A simple function
function foo(a, b) {
  snippet.log("a is " + a);
  snippet.log("b is " + b);
}

// Create a new one that, when called, will call the original passing in
// 1 as the first argument and then passing in any further arguments,
// preserving the `this` it was called with
var f = foo.curry(1);

// Call it
f(2); // "a is 1" / "b is 2"
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="//tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

is there a way to do this by creating an object literal

不,创建函数的唯一方法是从函数开始。您不能将非函数对象变成函数。

关于javascript - 同时是一个函数和一个对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33097986/

有关javascript - 同时是一个函数和一个对象?的更多相关文章

  1. ruby - 如何从 ruby​​ 中的字符串运行任意对象方法? - 2

    总的来说,我对ruby​​还比较陌生,我正在为我正在创建的对象编写一些rspec测试用例。许多测试用例都非常基础,我只是想确保正确填充和返回值。我想知道是否有办法使用循环结构来执行此操作。不必为我要测试的每个方法都设置一个assertEquals。例如:describeitem,"TestingtheItem"doit"willhaveanullvaluetostart"doitem=Item.new#HereIcoulddotheitem.name.shouldbe_nil#thenIcoulddoitem.category.shouldbe_nilendend但我想要一些方法来使用

  2. ruby-on-rails - 按天对 Mongoid 对象进行分组 - 2

    在控制台中反复尝试之后,我想到了这种方法,可以按发生日期对类似activerecord的(Mongoid)对象进行分组。我不确定这是完成此任务的最佳方法,但它确实有效。有没有人有更好的建议,或者这是一个很好的方法?#eventsisanarrayofactiverecord-likeobjectsthatincludeatimeattributeevents.map{|event|#converteventsarrayintoanarrayofhasheswiththedayofthemonthandtheevent{:number=>event.time.day,:event=>ev

  3. ruby - 使用 Vim Rails,您可以创建一个新的迁移文件并一次性打开它吗? - 2

    使用带有Rails插件的vim,您可以创建一个迁移文件,然后一次性打开该文件吗?textmate也可以这样吗? 最佳答案 你可以使用rails.vim然后做类似的事情::Rgeneratemigratonadd_foo_to_bar插件将打开迁移生成的文件,这正是您想要的。我不能代表textmate。 关于ruby-使用VimRails,您可以创建一个新的迁移文件并一次性打开它吗?,我们在StackOverflow上找到一个类似的问题: https://sta

  4. ruby-on-rails - Rails - 一个 View 中的多个模型 - 2

    我需要从一个View访问多个模型。以前,我的links_controller仅用于提供以不同方式排序的链接资源。现在我想包括一个部分(我假设)显示按分数排序的顶级用户(@users=User.all.sort_by(&:score))我知道我可以将此代码插入每个链接操作并从View访问它,但这似乎不是“ruby方式”,我将需要在不久的将来访问更多模型。这可能会变得很脏,是否有针对这种情况的任何技术?注意事项:我认为我的应用程序正朝着单一格式和动态页面内容的方向发展,本质上是一个典型的网络应用程序。我知道before_filter但考虑到我希望应用程序进入的方向,这似乎很麻烦。最终从任何

  5. ruby-on-rails - 渲染另一个 Controller 的 View - 2

    我想要做的是有2个不同的Controller,client和test_client。客户端Controller已经构建,我想创建一个test_clientController,我可以使用它来玩弄客户端的UI并根据需要进行调整。我主要是想绕过我在客户端中内置的验证及其对加载数据的管理Controller的依赖。所以我希望test_clientController加载示例数据集,然后呈现客户端Controller的索引View,以便我可以调整客户端UI。就是这样。我在test_clients索引方法中试过这个:classTestClientdefindexrender:template=>

  6. ruby-on-rails - 如何验证非模型(甚至非对象)字段 - 2

    我有一个表单,其中有很多字段取自数组(而不是模型或对象)。我如何验证这些字段的存在?solve_problem_pathdo|f|%>... 最佳答案 创建一个简单的类来包装请求参数并使用ActiveModel::Validations。#definedsomewhere,atthesimplest:require'ostruct'classSolvetrue#youcouldevencheckthesolutionwithavalidatorvalidatedoerrors.add(:base,"WRONG!!!")unlesss

  7. Ruby 写入和读取对象到文件 - 2

    好的,所以我的目标是轻松地将一些数据保存到磁盘以备后用。您如何简单地写入然后读取一个对象?所以如果我有一个简单的类classCattr_accessor:a,:bdefinitialize(a,b)@a,@b=a,bendend所以如果我从中非常快地制作一个objobj=C.new("foo","bar")#justgaveitsomerandomvalues然后我可以把它变成一个kindaidstring=obj.to_s#whichreturns""我终于可以将此字符串打印到文件或其他内容中。我的问题是,我该如何再次将这个id变回一个对象?我知道我可以自己挑选信息并制作一个接受该信

  8. ruby - 在没有 sass 引擎的情况下使用 sass 颜色函数 - 2

    我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re

  9. ruby-on-rails - 如果 Object::try 被发送到一个 nil 对象,为什么它会起作用? - 2

    如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象

  10. ruby - 为什么 SecureRandom.uuid 创建一个唯一的字符串? - 2

    关闭。这个问题需要detailsorclarity.它目前不接受答案。想改进这个问题吗?通过editingthispost添加细节并澄清问题.关闭8年前。Improvethisquestion为什么SecureRandom.uuid创建一个唯一的字符串?SecureRandom.uuid#=>"35cb4e30-54e1-49f9-b5ce-4134799eb2c0"SecureRandom.uuid方法创建的字符串从不重复?

随机推荐