如何使用ECMAScript 5定义默认的getter和setter? [英] How can I define a default getter and setter using ECMAScript 5?

查看:171
本文介绍了如何使用ECMAScript 5定义默认的getter和setter?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何为原型指定默认的getter?
使用默认的getter我的意思是在调用 obj.undefinedProperty123 时调用的函数。

How can I specify a default getter for a prototype? With default getter I mean a function that is called if obj.undefinedProperty123 is called.

I尝试了Object.prototype.get = function(property){..},但在这种情况下不会调用它。

I tried Object.prototype.get = function(property) {..} but this is not called in this case.

推荐答案

In ECMAScript 5,您只能通过 Object.defineProperty

In ECMAScript 5, you can only intercept get/set operations on specific named properties (not universally all properties) via Object.defineProperty:

Object.defineProperty(someObj, "someProp", {
    get: function() {
        console.log("you tried to get someObj.someProp");
        return "foo";
    }
});

这里, get 函数将运行任何时间代码试图读取 someObj.someProp

Here, the get function will run any time code tries to read someObj.someProp.

在即将发布的ECMAScript 6草案中,这可以通过< a href =https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy =nofollow noreferrer>代理。代理具有底层目标对象和set / get函数。只要在任何代理的属性上发生set或get操作,就会运行相应的函数,将代理的目标对象,使用的属性名称和集合中使用的值作为参数设置尝试。

In the upcoming ECMAScript 6 draft, this will be possible via proxies. A proxy has an underlying target object and set/get functions. Any time a set or get operation happens on any of a proxy's properties, the appropriate function runs, taking as arguments the proxy's target object, property name used, and the value used in a set attempt.

var proxyHandler = {
    get: function(obj, name){
        console.log("you're getting property " + name);
        return target[name];
    },
    set: function(obj, name, value) {
        console.log("you're setting property " + name);
        target[name] = value;
    }
}

var underlyingObj = {};

// use prox instead of underlyingObj to use get/set interceptor functions
var prox = new Proxy(underlyingObj, proxyHandler);

此处设置为在 prox 将导致设置 / 获取函数运行。

Here, setting to getting property values on prox will cause the set/get functions to run.

这篇关于如何使用ECMAScript 5定义默认的getter和setter?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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