2016-04-22 37 views
0

我已經用constructer Vector(它有兩個參數)編寫了一個代碼,我希望通過原型函數傳遞不同的參數集合,並且想總結兩組參數的值。Javascript中的Constructer不返回原型函數傳遞的正確值

但是我正面臨打印最終Vector的問題。

function Vector(x, y) { 

    this.x = x; 

    this.y = y; 

    console.log(x, y);//initially this prints (3,3) 

    return (x, y); 
} 



Vector.prototype.plus = function (a, b) { 

    this.x = this.x + a; 
    this.y = this.y + b; 
    console.log(this.x, this.y);// After passing (1,9) it prints (4,12)but  
    return (this.x, this.y); //after returning (this.x, this.y) it 
           //prints only Y coordinate as 12 
} 

var type_vector = new Vector(3, 3); 

console.log(type_vector.plus(1, 9)); 

輸出:(3,3),(4,12),12

+2

我不認爲你可以返回多個值的parens那樣。相反,您需要返回一個對象'return {y:this.y,x:this.x};' – evolutionxbox

+0

我不認爲'return(x,y);'表示您認爲它的意思。 –

+0

在JavaScript中,U不能使用'return(x,y);' – codetalker

回答

0

那麼,在JavaScript中,如果你想返回您可以使用[]符號的數組。

差異。這與你版本:

function Vector(x, y) { 
    this.x = x; 
    this.y = y; 
    console.log(x, y); 
    return this; 
} 
Vector.prototype.plus = function(a, b) { 
    this.x = this.x + a; 
    this.y = this.y + b; 
    console.log(this.x, this.y); 
    return [this.x, this.y]; 
}; 
var type_vector = new Vector(3, 3); 
console.log(type_vector.plus(1, 9)); 
2

我相信你從蟒蛇的背景是,因爲有(X,Y)返回一個元組。在JS中,如果你返回(x,y);它將是右括號中的值(在本例中爲y)。你必須爲你的目標使用一個對象或數組。

試試這個控制檯上:

var a = (3, 4, 5, 6); 
console.log(a);