我想创建一个自己的javascript类。我的问题是,如何根据上下文创建具有两个不同效果的函数。
以下是一个例子:
function Matrix(str) {
this.G = 2 dim array;
this.e = function(x,y){
G[x][y] = 3 // if the user types myGraph.e(1,1) = 3;
return G[x][y] // if user call myGraph.e(1,1);
}
那么如何只用一个函数才能得到两个不同的结果呢? myGraph.e(1,1) = 3
和myGraph.e(1,1)
Thx!
答案 0 :(得分:1)
这是不可能的,但你可以简单地采取第三个论点:
this.e = function( x , y, value){
switch( arguments.length ) {
case 3: this.G[x][y] = value; return; // myGraph.e( 1, 1, 3 );
case 2: return this.G[x][y]; // myGraph.e( 1, 1 );
default: throw new TypeError( "..." );
}
}
答案 1 :(得分:0)
略微修改@ Esalija的回答:
this.e = function(x, y, value) {
if (typeof value !== 'undefined') {
this.G[x][y] = value;
}
return this.G[x][y]; // always return the value
}
注意:2-D数组的第一个维度代表y
而不是x
更为常见。