有没有办法在javascript对象中代理变量?

有没有办法在javascript对象中代理变量?,javascript,Javascript,考虑到我使用的是John Resig的类(在这里找到:),javascript对象是否有办法将其变量代理给另一个对象 例如: var Car = Class.extend({ init: function(mileage, color, type) { this.mileage = mileage; this.color = color; this.type = carDatabase[type]; } )); // Th

考虑到我使用的是John Resig的类(在这里找到:),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
因此,在上面的示例中,我是否可以代理将
类型
转发到Car类本身,而不复制
类型
的内容

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

我知道下划线和jQuery都提供扩展方法,但它们似乎将内容复制到原始对象中。我还考虑了fly-weight模式(我认为这是一种过激的模式,我会得出与上面相同的症结所在)。

您可以使用它来支持为属性定义get/set方法

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

既然你提到了约翰·雷西格,他有一篇很好的博客文章“”,虽然有点老了,但读起来还是不错的。这是在2009年5月写的,他在帖子的早期指出,一些示例和规范可能会改变。

是的。使用ES6 Proxy()可以为属性get和set事件创建陷阱

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 
    }
}

@dc5的答案是正确的,但它的性能可能比复制数据差,而且浏览器支持也少。为什么不使用缓冲区呢<代码>var car=myCar.type然后使用car.year…@technosaurus,因为car会错过某个实例特有的颜色/里程等内容。其他元素是共享的(如发动机和公司),但元素/属性(如里程)仅适用于特定的汽车