2016-10-01 68 views
0

我在寫一個THREE.js圖形程序,並且想用Javascript創建一個BodyPart類,但是我不能調用這些方法。下面的代碼打印「調用測試」,但不是「調用測試」。我試過把功能測試外部BodyPart並將其與原型相關聯,但也會發生同樣的問題。這段代碼有什麼問題?無法在JavaScript類中調用函數

 function BodyPart (name){   
      this.name = name; 
      this.test = function(){ 
      alert('called test'); 
      }     
      this.geometry = new THREE.BoxGeometry(1, 1, 1); 
      this.material = new THREE.MeshNormalMaterial({ color: 0x00ff00 });    
      return new THREE.Mesh(this.geometry, this.material); 
      } 


     var backFoot = new BodyPart("Back foot"); 
     alert('calling test');   

     backFoot.test(); 

回答

1

你的問題是,你從你的函數返回THREE.mesh:

return new THREE.Mesh(this.geometry, this.material); 

這樣做是爲了網格而不是一個屬性:

this.mesh= new THREE.Mesh(this.geometry, this.material); 
0

這是因爲你返回THREE.Mesh從函數中,並將其保存到backFoot。因此,你的有效嘗試做:

new THREE.Mesh(this.geometry, this.material).test(); 

當你調用test這樣的:

backFoot.text(); 

這是無效的,因爲THREE.Mesh不具備的功能test。不要從函數返回,設置,作爲一個屬性:

function BodyPart(name) { 
 
    this.name = name; 
 
    this.test = function() { 
 
    alert('called test'); 
 
    } 
 
    this.geometry = new THREE.BoxGeometry(1, 1, 1); 
 
    this.material = new THREE.MeshNormalMaterial({ 
 
    color: 0x00ff00 
 
    }); 
 
    this.mesh = new THREE.Mesh(this.geometry, this.material); //Now, as a property instead of returning. 
 
} 
 

 
var backFoot = new BodyPart("Back foot"); 
 
alert("calling test"); 
 
backFoot.test(); 
 
//Access the mesh with backFoot.mesh
<script src="//cdnjs.cloudflare.com/ajax/libs/three.js/r70/three.min.js"></script>

+0

嗯,我認爲這可能最終穿透我的厚頭骨。只要我能夠調用backFoot.test(),您的解決方案就可以工作,但表示後腳的多維數據集不會出現在圖像中。看起來,製作一個對象的成本是網格現在是對象的屬性,而不是對象本身。是對的嗎?因此,我現在不需要調用scene.add(backfoot),而是需要調用scene.add(backfoot.mesh) - 事實上,當我開始創建整個身體部位時,scene.add(<任何身體部位> .mesh)。 – struggling

+0

@struggling是的,這是一個屬性。返回會導致各種麻煩,我不建議這樣做。構造一個對象通常會給出一個構造函數類型的新對象,但是會覆蓋它 – Li357