Javascript - 捕获对象属性的访问权限 [英] Javascript - catch access to property of object

查看:117
本文介绍了Javascript - 捕获对象属性的访问权限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以捕获对象的(任何)属性何时被访问或尝试访问?

Is it possible to capture when a (any) property of an object is accessed, or attempting to be accessed?

示例:

我创建了自定义对象 Foo

var Foo = (function(){
    var self = {};
    //... set a few properties
    return self;
})();

然后针对 Foo 采取行动 - 有人试图访问财产 bar

Then there is some action against Foo - someone tries to access property bar

Foo.bar

是否有方法(原型,可能)来捕捉这个?在 Foo 上可能未定义 bar 。我可以捕获任何尝试访问未定义属性的功能。

Is there way (prototype, perhaps) to capture this? bar may be undefined on Foo. I could suffice with capturing any attempted access to undefined properties.

例如,如果在 Foo 上未定义 bar ,并尝试 Foo.bar ,例如:

For instance, if bar is undefined on Foo, and Foo.bar is attempted, something like:

Foo.prototype.undefined = function(){
    var name = this.name; //name of property they attempted to access (bar)
    Foo[name] = function(){
        //...do something
    };
    return Foo[name];
}

但功能性,与我的例子不同。

But functional, unlike my example.

概念

Foo.* = function(){
}

背景

如果我有一个自定义函数,每次调用此函数时我都可以监听(见下文)。只是想知道是否可以进行财产访问。

If I have a custom function, I can listen for every time this function is called (see below). Just wondering if it's possible with property access.

Foo = function(){};
Foo.prototype.call = function(thisArg){
    console.log(this, thisArg);
    return this;
}


推荐答案

这将在ECMAScript6中实现,现在可以在Firefox上使用新的代理内容。在那之前,不,我担心没有办法进入链条。

This will be possible in ECMAScript6, and is possible right now on Firefox, using the new proxy stuff. Until then, no, I'm afraid there's no way to hook into the chain.

我花了一段时间,但我终于找到了这个问题。有关代理等所有详细信息,请参阅该答案。

It took me a while, but I finally found my previous answer to this question. See that answer for all the details on proxies and such.

以下是该答案的代理示例:

Here's the proxy example from that answer:

var obj = new Proxy({}, {
    get: function(target, name) {
        if (!(name in target)) {
            console.log("Getting non-existant property '" + name + "'");
            return undefined;
        }
        return target[name];
    },
    set: function(target, name, value) {
        if (!(name in target)) {
            console.log("Setting non-existant property '" + name + "', initial value: " + value);
        }
        target[name] = value;
    }
});

console.log("[before] obj.foo = " + obj.foo);
obj.foo = "bar";
console.log("[after] obj.foo = " + obj.foo);

实时复制 (目前仅适用于Firefox) | 来源

运行时,输出:

Getting non-existant property 'foo'
[before] obj.foo = undefined
Setting non-existant property 'foo', initial value: bar
[after] obj.foo = bar

这篇关于Javascript - 捕获对象属性的访问权限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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