簡體   English   中英

使用類和原型模式未定義組件的屬性

[英]Properties of component are undefined using class and prototype pattern

我已經在JavaScript中使用了類和原型模式。 我制作了一個名為NavigatieButton的函數,並構造了一個包含三個屬性的構造函數,分別命名為locationrotationnavigatie

NavigatieButton的原型中,我制作了一個名為init的函數,該函數必須呈現“組件”。

render函數中,我使用以下代碼創建NavigatieButton的新實例:

var navBtn = new NavigatieButton('0 0 0');

但是,如果我調用init ,則屬性locationrotationnavigatie是未定義的。

在這里您可以找到我編寫的代碼。

 "use strict"; function NavigatieButton(location) { this.location = location; } NavigatieButton.prototype.init = function() { var element = document.createElement('a-entity'); element.setAttribute('location', this.location); // Here I'm adding some other nodes to the `element` variable. return element; }; (function() { function render() { var el = document.createElement('div'); for (var i = 7; i--;) { var navBtn = new NavigatieButton('0 0 0'); var comp = NavigatieButton.prototype.init(); el.appendChild(comp); } console.log(el); } render(); })(); 

打開瀏覽器的控制台以查看記錄的數據。 在下面,您可以找到已記錄數據的摘要。

<div>
  <!-- 7 thimes this code: -->
  <a-entity location="undefined" rotation="undefined">
    <a-image src="./assets/images/navigationOuterCircle.png"></a-image>
    <a-image src="./assets/images/navigationInnerCircle.png" scale="0.5 0.5 0.5"></a-image>
  </a-entity>
  <!-- Till here -->
</div>

我的代碼有什么問題? 為什么我總是未定義而不是輸入?

PS 1:我正在關注本文: 定義JavaScript類的3種方法 (請參見標題1.2)

PS 2:我正在使用來創建WebVR。

代替

  var comp = NavigatieButton.prototype.init();

您必須使用剛剛創建的對象調用.init()

  var comp = navBtn.init();

.init()函數將在原型中找到,而當它被稱為正確的方法的價值this將是對一個參考navBtn你創建的對象。

您正在直接調用NavigatieButton構造函數的init函數,它不是一個新創建的對象。

使用navBtn.init(); 而不是NavigatieButton.prototype.init();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM