2012-12-09 39 views
0

我對JavaScript非常陌生,類和方法的工作方式讓我感到困惑。使用類中的變量調用類方法的Javascript

基本上我有這樣的代碼:

function container(x, y, z) { 
    this.x = x; 
    this.y = y; 
    this.z = z; 

    this.sumUp = function addUp(x, y, z) { 
    var a = x + y + z; 
    }; 
} 

我想要做的就是在其他地方在我的代碼使用的容器內定義的函數,在容器使用的值。我如何真的去做這件事?

沿

container1 = new container (1, 2, 3); 
container.sumUp(this.x, this.y, this.z); 

或者類似的東西,東西線。我非常困惑,並且認爲我正在做的事情都是錯誤的。

回答

2

我想你想somwthing這樣的:

function Container(x, y, z){ 
    this.x = x; 
    this.y = y; 
    this.z = z; 

    this.sumUp = function addUp(x, y, z){ 
    alert(this.x + this.y + this.z); 
    }; 
} 

container_instance = new Container(1, 2, 3); 
container_instance.sumUp(); 

但我建議:

function Container(x, y, z){ 
    this.x = x; 
    this.y = y; 
    this.z = z; 
} 

Container.prototype.sumUp = function addUp(x, y, z){ 
    alert(this.x + this.y + this.z); 
}; 

container_instance = new Container(1, 2, 3); 
container_instance.sumUp(); 

也就是說它是如何工作(短):

在JavaScript中你有objects,他們像哈希:

var obj = { 
    'a': 1, 
    'b': 2, 
    'c': 3 
}; 

,您可以通過按鍵獲取或設置值:

alert(obj.a); // alerts 1 
alert(obj['a']); // same thing 
obj['c'] = 4; 

在你的情況Container是功能,將建立你的對象。當你做new Container(1, 2, 3);它創建一個空的對象,並在對象的上下文中執行的功能。

+1

sumUp/addUp爲什麼需要使用未使用的參數?似乎毫無意義。 – johusman

+0

@ johusman當然他們不會受傷。 –

+0

注意'new'也設置了對象的'[[prototype]]' –

1
function Container(x, y, z){ 
    this.x = x; 
    this.y = y; 
    this.z = z; 
} 
// There is no point to put parameters there since they are already instance variables. 
Container.prototype.sumUp = function addUp(){ 
    alert(this.x + this.y + this.z); 
}; 

container_instance = new Container(); 
container_instance.sumUp(); 
相關問題