鉴于我正在使用 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
.
理想情况下,我宁愿 type myCar.company
,而不是myCar.type.company
Class 的一致性。
我知道 underscore 和 jQuery 都提供扩展方法,但它们似乎将内容复制到原始对象中。我还考虑了飞行重量模式(我认为这是矫枉过正,我会遇到与上述相同的症结)。