Javascript 向函数添加值访问器
我似乎对下面的代码有一些问题:Javascript 向函数添加值访问器,javascript,node.js,Javascript,Node.js,我似乎对下面的代码有一些问题: var chart = function(d) { var width = 0; // default width var height = 0; // default height function my() { // generate chart here, using `width` and `height` console.log("The Input is " + d); console.log("c
var chart = function(d) {
var width = 0; // default width
var height = 0; // default height
function my() {
// generate chart here, using `width` and `height`
console.log("The Input is " + d);
console.log("chart height is " + my.height());
console.log("chart width is " + my.width());
}
my.width = function(value) {
if (!arguments.length) return width;
width = value;
return width;
};
my.height = function(value) {
if (!arguments.length) return height;
height = value;
return height;
};
return my;
}
当我设置var myvar=chart()时,宽度(20)
然后调用myvar.width()。我觉得我已经接近一个解决方案了,但我不太明白如何解决这个问题
我对使用get/set方法还不熟悉,所以如果能让我走上正确的道路,我将不胜感激
我使用可重用的图表作为基础
编辑更新:我希望在my()函数中可以访问输入的宽度和高度。您打算这样做吗
function chart(d) {
var width = 0; // default width
var height = 0; // default height
function my() {
// generate chart here, using `width` and `height`
console.log("The Input is " + d);
console.log("chart height is " + this.height());
console.log("chart width is " + this.width());
}
my.prototype.width = function(value) {
if (!arguments.length) return width;
width = value;
return this;
};
my.prototype.height = function(value) {
if (!arguments.length) return height;
height = value;
return this;
};
return new my();
}
var x = new chart().width(5).height(7); // sets width to 5 and height to 7
x.width() // returns 5
x.height() // returns 7
您可以返回函数my,而不是调用函数my作为回报
这应该行得通
var chart = function(d) {
var width = 0; // default width
var height = 0; // default height
function my() {
// generate chart here, using `width` and `height`
console.log("The Input is " + d);
console.log("chart height is " + my.height());
console.log("chart width is " + my.width());
}
my.width = function(value) {
if (!arguments.length) return width;
width = value;
return width;
};
my.height = function(value) {
if (!arguments.length) return height;
height = value;
return height;
};
return my;
}
然后
var myvar=chart();
myvar.宽度(20);
myvar.width()代码>
这将给你20个我想我找到了一个解决方案,我想我的问题有点含糊不清
var chart = function(d) {
var width = 0; // default width
var height = 0; // default height
function my() {
// generate chart here, using `width` and `height`
console.log(d);
console.log("width " + width + " height " + height);
}
my.width = function(value) {
if (!arguments.length) return width;
width = value;
return my;
};
my.height = function(value) {
if (!arguments.length) return height;
height = value;
return my;
};
return my;
}
然后在主代码中编写chart(“Test”)()
来调用内部函数。您的chart
函数不会返回任何内容。您可能根本不想将构造函数和原型包装在chart
函数中。这将在每次通话中重新创建它们。谢谢,我已经更新了我的代码。我希望my()函数根据输入的高度和宽度生成一个图形。我似乎遇到的问题是,my()函数没有在最后运行。