只有一个javascript类的两个效果

时间:2012-10-28 08:36:04

标签: javascript class graph

我想创建一个自己的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) = 3myGraph.e(1,1)

Thx!

2 个答案:

答案 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更为常见。