[英]Properties of component are undefined using class and prototype pattern
I've made use of the class and prototype pattern in JavaScript. 我已经在JavaScript中使用了类和原型模式。 I've made a function named
NavigatieButton
and got a constructor of three attributes named location
, rotation
and navigatie
. 我制作了一个名为
NavigatieButton
的函数,并构造了一个包含三个属性的构造函数,分别命名为location
, rotation
和navigatie
。
In the prototype of NavigatieButton
, I've maked a function named init
that must render a "component". 在
NavigatieButton
的原型中,我制作了一个名为init
的函数,该函数必须呈现“组件”。
Inside the render
function I make a new instance of NavigatieButton
using code below: 在
render
函数中,我使用以下代码创建NavigatieButton
的新实例:
var navBtn = new NavigatieButton('0 0 0');
But if I call init
, the properties location
, rotation
and navigatie
are undefined. 但是,如果我调用
init
,则属性location
, rotation
和navigatie
是未定义的。
Here you could find my code I've made. 在这里您可以找到我编写的代码。
"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(); })();
Open the console of your browser to see the logged data. 打开浏览器的控制台以查看记录的数据。 Below you could find a snippet of the logged data.
在下面,您可以找到已记录数据的摘要。
<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>
What's wrong with my code? 我的代码有什么问题? Why I've always undefined instead of my input?
为什么我总是未定义而不是输入?
PS 1: I'm following this article: 3 ways to define a JavaScript class (see heading 1.2) . PS 1:我正在关注本文: 定义JavaScript类的3种方法 (请参见标题1.2) 。
PS 2: I'm using aframe to create WebVR. PS 2:我正在使用aframe来创建WebVR。
Instead of 代替
var comp = NavigatieButton.prototype.init();
you must call .init()
with the object you just created: 您必须使用刚刚创建的对象调用
.init()
:
var comp = navBtn.init();
The .init()
function will be found on the prototype, and when it's called the correct way the value of this
will be a reference to the navBtn
object you created. 该
.init()
函数将在原型中找到,而当它被称为正确的方法的价值this
将是对一个参考navBtn
你创建的对象。
You are calling init function of NavigatieButton
constructor directly which is not a newly created object. 您正在直接调用
NavigatieButton
构造函数的init函数,它不是一个新创建的对象。
Use navBtn.init();
使用
navBtn.init();
instead of NavigatieButton.prototype.init();
而不是
NavigatieButton.prototype.init();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.