仅适用于对象实例,不幸的prototype
是您没有。如果你有这样的构造函数:
function Color(r,g,b,a){
for (var i=0; i<4; i++)
this[i] = arguments[i];
}
它可以与
Object.defineProperty(Color.prototype, "r", {
get: function() { return this[0]; } // setter analogous
};
但是,这些Color
实例不是数组。您可以给它们一个length
属性并让它们继承自Array.prototype
,但它们不会是真正的数组。@Trouts 解决方案有点像这样,我会说这没关系,因为颜色真的不是数组(你不能推送第五个值等)。
color
另一种方法是使用这些属性扩展从 getter 返回的数组。每次有人访问该值时,您都可以这样做(就像您目前所做的那样,您在 getter 中创建一个新数组),但我建议您应该返回相同的实例,传播任何更改。您当前的属性定义类似于“setColor”和“getCurrentColor”。
所以,实际上你想要两个不同的东西:Color
每个值具有多个属性的对象(即0
== r
);和一个全局变量的设置器,color
它接受数组并在相应对象上设置单个值。
// version with private values
function Color(r, g, b, a) {
// r, g, b and a are private-scoped variables
var desc = {
"0": {
get:function(){return r;},
set:function(val){ if(+val<256&&val>=0) r=+val;}
},
…
}
// use those property descriptors multiple times
desc.r = desc[0];
…
Object.defineProperties(this, desc);
}
// or version with public and unlimited read/write access to the properties:
function Color(r,g,b,a){
for (var i=0; i<4; i++)
this[i] = arguments[i];
}
Object.defineProperties(Color.prototype, {
r: { get:function(){return this[0];}, set:function(r){this[0]=r;} },
…
}
// and for both versions we can add array-like methods on the prototype
var cprot = Color.prototype, aprot = Array.prototype;
Object.defineProperty(cprot, "length", {value:4});
// we only need accessor functions here, nothing which changes the array [length]
cprot.map = aprot.map;
cprot.reduce = aprot.reduce;
cprot.slice = aprot.slice;
cprot.join = aprot.join;
// you might want to add other utilities like
cprot.toString = function() {
return "rgba("+this.join(",")+")"; // using array method from above
};
cprot.getHex = function() {
function hex(n) { return (n<16?"0":"") + n.toString(16); }
return "#"+this.slice(0, 3).map(hex).join("");
};
然后,您的颜色值设置器:
function defineColorProperty(obj, prop, color) {
// again, color is private-scoped
if (!color || !(color instanceof Color)) color = new Color(0, 0, 0, 0);
Object.defineProperty(obj, prop, {
get: function(){ return color; }, // a cool Color instance!
set: function(val) {
if (Object(val)!==val) return; // accept objects (including arrays)
for (var i=0; i<4 && i<val.length; i++)
color[i] = val[i];
},
enumberable: true
});
return color;
}
// usage:
> defineColorProperty(window, "color");
Object[Color]: 0, 0, 0, 0
> color = [255, 0, 120, 1];
> color.r = 42;
> color[0]
42
> color = [0, 0];
> ""+color
"rgba(0,0,120,1)"
> var x = color;
> x.b = 255;
> x.getHex()
"#0000FF"