我有这段代码:
var rect2 = new drawRect({
h: 100,
w: 100,
x: 280,
y: 20,
colour: '8CB5CF',
name: 'Office 2'
}
是否可以读取我传递给drawRect的属性? 我的第一个想法是:
alert(rect2.h)
但是这导致了undefined
,没想到它真的有效,但我不知道如何处理这个问题。
我对javascript很新。感谢。
编辑:对不起,这是drawRect:
function drawRect(rectOptions){
var ctx = document.getElementById('canvas').getContext('2d');
ctx.fillStyle = rectOptions.colour;
ctx.fillRect(rectOptions.x,rectOptions.y,rectOptions.h,rectOptions.w);
ctx.font = '12px sans-serif';
ctx.fillText(rectOptions.name, rectOptions.w + rectOptions.x, rectOptions.h + rectOptions.y);
}
这是完整的代码:Full code
答案 0 :(得分:0)
在drawRect
函数内部,您可以添加一行以向option
构造的对象添加drawRect
属性。
function drawRect(rectOptions) {
this.options = rectOptions;
//...
}
然后你可以做
var rect2 = new drawRect({ /* ... */ });
alert(rect2.options.h);
或者,您可以让drawRect
返回传递给它的选项。
function drawRect(rectOptions) {
//...
return rectOptions;
}
然后你可以做,就像你最初尝试的那样,
alert(rect2.h);
答案 1 :(得分:0)
var rect2 = new drawRect({
h: 100,
w: 100,
x: 280,
y: 20,
colour: '8CB5CF',
name: 'Office 2'
})
function drawRect(rectOptions){
//your code
return rectOptions;//you have to return the value
}
alert(rect2.h);//alerts 100