有没有一种方法可以在javascript对象中代理变量

Is there a way to proxy variables within a javascript object?

本文关键字:javascript 对象 变量 代理 方法 一种 有没有      更新时间:2023-09-26

假设我使用的是John Resig的类(在这里找到:class),javascript对象有没有办法将其变量代理到另一个对象?

示例:

var Car = Class.extend({
    init: function(mileage, color, type) {
         this.mileage = mileage;
         this.color = color;
         this.type = carDatabase[type];
    }
));
// This would be loaded in as a datasource, not sitting in global 
// space like this. 
var carDatabase = {
     "Falcon": {
        "year": 2013,
        "engine": "Inline 8",
        "company": "Ford"
     },
     "Commodore": {
        "year": 2012,
        "engine": "V8",
        "company": "Holden"
     },
     // etc etc
};
// Using the Car class somewhere:
var myCar = new Car(10000, "blue", "Falcon");
console.log(myCar.color); // blue
console.log(myCar.type.year); // 2013
console.log(myCar.type.company); // Ford

因此,在上面的例子中,我可以代理将type转发到Car类本身中吗?而不复制type的内容。

理想情况下,为了类的一致性,我宁愿键入myCar.company,而不是myCar.type.company

我知道underline和jQuery都提供了扩展方法,但它们似乎将内容复制到了原始对象中。我也考虑过蝇重模式(我认为这是过分的,我会得出与上述相同的症结所在)。

您可以使用defineProperty,它支持为属性定义get/set方法等。

参考的MDN文章也有一个兼容性表,但在所有浏览器的最新版本中通常都支持它,但有一些限制。

既然你提到了John Resig,他有一篇很好的博客文章"ECMAScript 5对象和属性",这篇文章有点老,但读起来还是不错的。它写在2009年5月,他在帖子的早期表示,一些示例和规格可能会改变。

是。使用ES6Proxy(),您可以为属性获取和设置事件创建陷阱。

const handler = {
    get(object, property) { 
        if(object.hasOwnProperty(property)){
            for(var prop in object[property]){
                this[prop] = object[property][prop] //set class instance props
            }               
        }
        return object[property]; // don't need to return
    }
};

var carDatabaseProxy = new Proxy(carDatabase, handler)
class Car {
    constructor(mileage,color,type){
         this.mileage = mileage;
         this.color = color;
         carDatabaseProxy[type]; // just need to get 
    }
}