什么是node's相当于Perl'神奇的“tie()”机制(挂钩/拦截对变量的访问)

What is node's equivalent of Perl's magic `tie()` mechanism (hooking into/intercepting access to variables)?

本文关键字:挂钩 机制 访问 变量 node 相当于 Perl 什么 神奇 tie      更新时间:2023-09-26

我正在寻找类似于这个例子的东西,通过用户定义的回调/钩子拦截对字符串、数组和对象变量的访问:

var foo = [];
tie( // hypothetical
    foo,
    {
        STORE: // callback triggered when assigning: foo[index] = value
        function(self, index, value) {
            if (value.match('fnord')) {
                self[index] = "Nothing to see here. Move along.";
                return;
            }
            self[index] = value;
        },
        FETCH: // callback triggered when accessing: foo[index]
        function(self, index) {
            if (42 == index) {
                return "This is The Answer.";
            }
            return self[index];
        }
    }
);

这个概念的工作实现的简单演示:

package Quux;
use Tie::Array ();
use base 'Tie::StdArray';
sub FETCH {
    my ($self, $index) = @_;
    return 'This is The Answer.' if 42 == $index;
    return $self->[$index];
}
sub STORE {
    my ($self, $index, $value) = @_;
    if ($value =~ 'fnord') {
        $self->[$index] = 'Nothing to see here. Move along.';
        return;
    }
    $self->[$index] = $value;
}
package main;
tie my @foo, 'Quux';
@foo = (undef) x 50;
print $foo[42];
$foo[0] = 'fnord';
print $foo[0];

完整文档:tie(概念),tie()(函数),tie::Array,magic

代理API大致相当于此功能。这是一个ES6特性,但V8已经为它提供了"实验性"支持(用--harmony--harmony-proxies启动节点以启用此特性)。以下是用代理重写的代码片段:

var foo = (function() {
    var obj = {};
    return Proxy.create({
        set: function(self, index, value) {
            if (value.match(/fnord/)) {
                obj[index] = "Nothing to see here. Move along.";
                return;
            }
            obj[index] = value;
        },
        get: function(self, index) {
            if (42 == index) {
                return "This is The Answer.";
            }
            return obj[index];
        }
    });
})();
console.log(foo[42]);
foo[0] = 'fnord';
console.log(foo[0]);