Javascript重载点 [英] Javascript overloading dot

查看:99
本文介绍了Javascript重载点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨有没有办法在javascript中重载'。'(点)和[]运算符。即如果我说obj.Name或obj ['Name']它应该通过传递Name作为参数来调用obj类中的公共方法。 python中使用属性方法提供的类似功能。但是在这里我希望将.Name作为参数传递给公共方法。

Hi is there a way to overload the '.'(dot) and [] operator in javascript. ie if I say obj.Name or obj['Name'] it should call a common method in the obj class by passing Name as argument. The similar kind of functionality available in python using property method. But here I want the ".Name" to be passed as argument to the common method.

就像这样......

like this..

function Data(){
    this.getValue(name){
        return '...'
    }
}

data = new Data()
name = data.Name 
name = data['Name']
//both should call data.getValue()


推荐答案

2010年答案 (请参阅下面的2013年更新)

不,您不能将属性名称查找重定向到您自己的函数。

No, you can't redirect property name lookups to your own function.

但是,从ECMAScript5开始,您可以使用getters和setters定义属性。这是一个尚未得到广泛支持的新功能,但是当它出现时,它会做一些模糊类似的功能。这包含在规范的几个部分中。因此,如果您以这种方式定义了所有属性,然后将实际请求发送到中央 getValue 函数,那么您最终会得到您想要的内容。有一天。 :-)除了它不会为不存在的属性调用 getValue

However, as of ECMAScript5, you can define properties with "getters" and "setters". This is a new feature which isn't widely-supported yet, but when it is, it will do something vaguely similar. This is covered in a couple of parts of the spec. So if you defined all of your properties that way, and then sent the actual request to your central getValue function, you'd end up with largely what you wanted. Someday. :-) Except that it won't call getValue for a property that doesn't exist.

2013年回答

这很快就会改变(并且已经拥有最新的Firefox用户):ECMAScript第6版将有代理的。它们在草案规范中定义,也在此页(但规范草案优先)。

This is going to change soon (and it already has for up-to-date Firefox users): ECMAScript 6th edition will have proxies. They're defined in the draft specification, and also on this page (but the spec drafts take precedence).

Proxies允许您创建对象是其他对象的真实代理(外观)。这是一个简单的示例,它将任何字符串的属性值转换为检索的所有上限:

Proxies let you create objects that are true proxies (facades) for other objects. Here's a simple example that turns any property values that are strings to all caps on retrieval:

var original = {"foo": "bar"};
var proxy = new Proxy(original, {
    get: function(target, name, receiver) {
        var rv = target[name];
        if (typeof rv === "string") {
            rv = rv.toUpperCase();
        }
        return rv;
    }
});

console.log("original.foo = " + original.foo); // "bar"
console.log("proxy.foo = " + proxy.foo);       // "BAR"

实例 | 来源

您不需要的操作override具有默认行为。在上面,我们覆盖的只是 get ,但是你可以勾选一整套操作。

Operations you don't override have their default behavior. In the above, all we override is get, but there's a whole list of operations you can hook into.

get 处理函数的参数列表中:

In the get handler function's arguments list:


  • target 是被代理的对象(在我们的例子中是原始)。

  • name (当然)是要检索的属性的名称。

  • receiver 是代理本身或从中继承的东西。在我们的例子中, receiver === proxy ,但如果将代理用作原型, receiver 可能是后代对象,因此它位于函数签名上(但最后,如果像上面的例子那样,你实际上并没有使用它,你可以随时把它关掉。)

  • target is the object being proxied (original, in our case).
  • name is (of course) the name of the property being retrieved.
  • receiver is either the proxy itself or something that inherits from it. In our case, receiver is === proxy, but if proxy were used as a prototype, receiver could be a descendant object, hence it being on the function signature (but at the end, so you can readily leave it off if, as with our example above, you don't actually use it).

这可以让你创建一个具有你想要的全能getter和setter功能的对象:

This lets you create an object with the catch-all getter and setter feature you want:

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);

实例 | 来源 (注意我是如何离开接收器关闭这些函数,因为我们不使用它。 receiver set 的可选第四个arg 。)

Live Example | Source (Note how I've left receiver off the functions, since we don't use it. receiver is an optional fourth arg on set.)

以上的输出是:

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

注意当我们尝试检索 foo 时,我们如何获得不存在的消息,当我们创建它时,但不是随后。

Note how we get the "non-existant" message when we try to retrieve foo when it doesn't yet exist, and again when we create it, but not subsequently.

这篇关于Javascript重载点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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