首页 \ 问答 \ 动态代理在JavaScript?(Dynamic proxies in javascript?)

动态代理在JavaScript?(Dynamic proxies in javascript?)

我可以通过做这样的事情来代理javascript中的单个函数(只记下内存,所以请耐心等待)

function addAroundAdvice(target){
    var targetFunction = target.aFunction;
    target.aFunction = new function(){
           invokePreCall();
           targetFunction.apply(target, arguments);
           invokePostCall();
    }
}

作为一名Java程序员,我认为这是一个动态代理。 每次我写这样的代码时,我认为有人必须创建一个非常聪明的库,它执行的常见代理操作至少比我能够做的要好10%。 我期待一些东西,比如正确截取任何给定对象的所有方法,这可能不是完全无关紧要的。 然后有不同类型的建议。 所以虽然我不期待scriptaculous的大小,但它肯定超过6行代码。

那么这些库在哪里?


I can proxy a single function in javascript by doing something like this (just jotted down from memory so bear with me)

function addAroundAdvice(target){
    var targetFunction = target.aFunction;
    target.aFunction = new function(){
           invokePreCall();
           targetFunction.apply(target, arguments);
           invokePostCall();
    }
}

Being a java programmer I'd think of this as a dynamic proxy. Every time I write code like this I think that someone must have made a really smart library that does the common proxying operations that is at least 10% better than what I can do in a hurry. I'd be expecting some stuff like correctly intercepting all methods for any given object, which may not be entirely trivial. Then there's different types of advice. So while I'm not expecting something the size of scriptaculous, it's certainly more than 6 lines of code.

So where are these libraries ?


原文:https://stackoverflow.com/questions/568581
更新时间:2023-11-04 18:11

最满意答案

始终注意编译器的警告。 如果您没有收到任何警告,请检查您的编译器设置。

$ gcc -Wall -O a.c
a.c: In function ‘main’:
a.c:6:5: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
     list_nums = malloc(argc * sizeof(int));
     ^
a.c:6:17: warning: incompatible implicit declaration of built-in function ‘malloc’
     list_nums = malloc(argc * sizeof(int));
                 ^
a.c:8:24: warning: assignment makes integer from pointer without a cast
         list_nums[i-1] = argv[i];
                        ^

第一个警告说没有声明malloc ; 你错过了#include <stdlib.h> 。 在大多数系统中,这不会导致实际问题。 第二个警告是同样问题的结果。

第三个警告表明存在问题。 argv是一个指向char的指针数组,因此argv[i]是指向char的指针。 list_nums指向一个整数数组。 所以你要指定一个整数的指针。 您打印出来的随机数字是内存中参数的地址。

您可以将字符串数组复制到字符串数组中。 在这种情况下,您需要将list_nums更改为char*数组,并使用%s说明符进行打印。

看来你打算将参数解释为整数。 如果要将参数(即字符串)转换为整数,则需要明确地执行此操作。 您可以使用atoi函数快速一次性代码,或strtol使用健壮的代码( atoi不允许错误检查)。

long *list_nums = malloc((argc-1) * sizeof(*list_nums));
char *end;
if (list_nums == NULL) {
    fprintf(stderr, "Not enough memory\n");
    return EXIT_FAILURE;
}
for (i = 1; i < argc; i++) {
    list_nums[i-1] = strtol(argv[i], &end, 0);
    if (*end != 0) {
        fprintf(stderr, "Invalid argument: %s\n", argv[i]);
        return EXIT_FAILURE;
    }
}
for (i = 0; i < argc-1; i++) {
    printf("%ld, ", list_nums[i]);
}

Always pay attention to your compiler's warnings. If you aren't getting any warnings, check your compiler settings.

$ gcc -Wall -O a.c
a.c: In function ‘main’:
a.c:6:5: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration]
     list_nums = malloc(argc * sizeof(int));
     ^
a.c:6:17: warning: incompatible implicit declaration of built-in function ‘malloc’
     list_nums = malloc(argc * sizeof(int));
                 ^
a.c:8:24: warning: assignment makes integer from pointer without a cast
         list_nums[i-1] = argv[i];
                        ^

The first warning says that malloc isn't declared; you're missing #include <stdlib.h>. On most systems this won't cause an actual problem. The second warning is a consequence of the same problem.

The third warning indicates a real problem. argv is an array of pointers to char, so argv[i] is a pointer to char. list_nums points to an array of integers. So you're assigning a pointer to an integer. The random-looking numbers that you're printing out are the addresses of the arguments in memory.

You can copy an array of strings into an array of strings. In this case, you need to change list_nums to an array of char*, and use the %s specifier for printing.

It seems that you intended to interpret the arguments as integers though. If you want to convert the arguments — which are strings — to integers, you need to do that explicitly. You can use the atoi function for quick throwaway code, or strtol for robust code (atoi doesn't permit error checking).

long *list_nums = malloc((argc-1) * sizeof(*list_nums));
char *end;
if (list_nums == NULL) {
    fprintf(stderr, "Not enough memory\n");
    return EXIT_FAILURE;
}
for (i = 1; i < argc; i++) {
    list_nums[i-1] = strtol(argv[i], &end, 0);
    if (*end != 0) {
        fprintf(stderr, "Invalid argument: %s\n", argv[i]);
        return EXIT_FAILURE;
    }
}
for (i = 0; i < argc-1; i++) {
    printf("%ld, ", list_nums[i]);
}

相关问答

更多
  • 始终注意编译器的警告。 如果您没有收到任何警告,请检查您的编译器设置。 $ gcc -Wall -O a.c a.c: In function ‘main’: a.c:6:5: warning: implicit declaration of function ‘malloc’ [-Wimplicit-function-declaration] list_nums = malloc(argc * sizeof(int)); ^ a.c:6:17: warning: incompatibl ...
  • 运行时库将跟踪分配的内存块。 保证正确释放块,给定初始指针由new返回。 虽然这可以在操作系统本身实现(理论上),但通常不会。 操作系统跟踪的是分配给整个流程的页面,而不是在这个抽象层次上分配的单个块。 The runtime library will keep track of allocated blocks of memory. It's guaranteed to deallocate the block correctly, given the initial pointer returned b ...
  • 使用线程专用变量可以做到这一点。 那些在以后的parallel区域持续存在: void func(...) { static double *buf; #pragma omp threadprivate(buf) #pragma omp parallel num_threads(nth) { buf = malloc(n * sizeof(double)); ... } #pragma omp parallel num_threads(nt ...
  • 没有必要重新发明轮子,C自从C99以来就称之为变长阵列VLA。 它只具有“普通”d维数组的语法,只是边界可能是可变的,并且它们不允许在文件范围内。 因为这样的对象可能会变得相对较大,所以不应该将它们分配到堆栈上,而应该像malloc一样 double (*A)[n][m] = malloc(sizeof(double[k][n][m])); 然后编译器帮助你完成所有索引计算,没有任何问题。 如果你想将这些动物传递给函数,你只需要小心地首先声明边界: void func(size_t k, size_t n ...
  • 不,全局数据不在堆栈上分配。 它们被静态分配,并且在编译时保留内存。 考虑这个问题的一个简单方法是考虑线程。 每个线程有一个堆栈。 但全局数据在线程之间共享。 所以全局数据不能在堆栈上分配。 其他类型的全局变量在堆上。 并非如此。 全局数据永远不会分配在堆上。 堆分配在运行时动态执行。 也许你有一个指针全局变量。 并且您为该指针分配一个动态数组。 在这种情况下,指针是全局的,但该数组是一个动态堆分配对象。 所以也许你有这样的代码: int *arr; .... arr = calloc(N, sizeof( ...
  • 在函数find_length ,读取整个文件,所以当您将文件指针传递给read_data ,它已经指向它的结尾。 您可以倒回指针 ,也可以关闭文件并重新打开它以便解析数据。 In function find_length, you read the whole file so when you pass the file pointer to read_data, it already points to the end of it. You can either rewind the pointer, o ...
  • 这条线 struct buff_ctrl* curr_buff = (buff + (i*sizeof(struct buff_ctrl))); 应该 struct buff_ctrl* curr_buff = buff + i; buff + i是指针算术,编译器已经考虑了buff指向的对象的大小。 通过执行i*sizeof(struct buff_ctrl)您将分配一个可能位于已分配内存之后的指针。 一般建议: 不要施放malloc 。 而不是使用sizeof() ,使用sizeof * ...
  • std::unique_ptr专门用于C ++ 11中的数组类型,因为它不适用于std::shared_ptr 。 所以std::unique_ptr会调用delete []但std::shared_ptr会默认调用delete 。 尽管在C ++ 17中这个行为已经改变了。 在C ++ 17中std::shared_ptr已经专门用于数组类型,并且使用std::shared_ptr将调用delete [] 。 ` std::unique_p ...
  • 以下是如何使用c ++ 11 new和delete运算符动态分配2D数组(10行和20列) 码: int main() { //Creation int** a = new int*[10]; // Rows for (int i = 0; i < 10; i++) { a[i] = new int[20]; // Columns } //Now you can access the 2D array 'a' like this a[x][y] //Destruction for (int ...
  • 我看到的一些事情: 首先,我希望你只是这几次打电话。 如果没有,那么您需要重构逻辑,以便只在算法的初始化阶段创建MPI_Datatype。 每次要发送信息时创建数据类型都很慢,原因很明显。 [如果数据类型的大小是唯一改变的东西,那么更好的选择就是停止使用MPI_Datatypes。 您似乎只是将它们用于连续数据,因此您可以在每次发送消息时正确指定MPI_Send / MPI_Recv的计数。 这是我在下面重写的方法] 其次,您发送的信息量似乎是错误的。 也就是说,您将sendVals设置为chunkSize ...

相关文章

更多

最新问答

更多
  • 您如何使用git diff文件,并将其应用于同一存储库的副本的本地分支?(How do you take a git diff file, and apply it to a local branch that is a copy of the same repository?)
  • 将长浮点值剪切为2个小数点并复制到字符数组(Cut Long Float Value to 2 decimal points and copy to Character Array)
  • OctoberCMS侧边栏不呈现(OctoberCMS Sidebar not rendering)
  • 页面加载后对象是否有资格进行垃圾回收?(Are objects eligible for garbage collection after the page loads?)
  • codeigniter中的语言不能按预期工作(language in codeigniter doesn' t work as expected)
  • 在计算机拍照在哪里进入
  • 使用cin.get()从c ++中的输入流中丢弃不需要的字符(Using cin.get() to discard unwanted characters from the input stream in c++)
  • No for循环将在for循环中运行。(No for loop will run inside for loop. Testing for primes)
  • 单页应用程序:页面重新加载(Single Page Application: page reload)
  • 在循环中选择具有相似模式的列名称(Selecting Column Name With Similar Pattern in a Loop)
  • System.StackOverflow错误(System.StackOverflow error)
  • KnockoutJS未在嵌套模板上应用beforeRemove和afterAdd(KnockoutJS not applying beforeRemove and afterAdd on nested templates)
  • 散列包括方法和/或嵌套属性(Hash include methods and/or nested attributes)
  • android - 如何避免使用Samsung RFS文件系统延迟/冻结?(android - how to avoid lag/freezes with Samsung RFS filesystem?)
  • TensorFlow:基于索引列表创建新张量(TensorFlow: Create a new tensor based on list of indices)
  • 企业安全培训的各项内容
  • 错误:RPC失败;(error: RPC failed; curl transfer closed with outstanding read data remaining)
  • C#类名中允许哪些字符?(What characters are allowed in C# class name?)
  • NumPy:将int64值存储在np.array中并使用dtype float64并将其转换回整数是否安全?(NumPy: Is it safe to store an int64 value in an np.array with dtype float64 and later convert it back to integer?)
  • 注销后如何隐藏导航portlet?(How to hide navigation portlet after logout?)
  • 将多个行和可变行移动到列(moving multiple and variable rows to columns)
  • 提交表单时忽略基础href,而不使用Javascript(ignore base href when submitting form, without using Javascript)
  • 对setOnInfoWindowClickListener的意图(Intent on setOnInfoWindowClickListener)
  • Angular $资源不会改变方法(Angular $resource doesn't change method)
  • 在Angular 5中不是一个函数(is not a function in Angular 5)
  • 如何配置Composite C1以将.m和桌面作为同一站点提供服务(How to configure Composite C1 to serve .m and desktop as the same site)
  • 不适用:悬停在悬停时:在元素之前[复制](Don't apply :hover when hovering on :before element [duplicate])
  • 常见的python rpc和cli接口(Common python rpc and cli interface)
  • Mysql DB单个字段匹配多个其他字段(Mysql DB single field matching to multiple other fields)
  • 产品页面上的Magento Up出售对齐问题(Magento Up sell alignment issue on the products page)