I've made use of the class and prototype pattern in JavaScript. I've made a function named NavigatieButton
and got a constructor of three attributes named location
, rotation
and navigatie
.
In the prototype of NavigatieButton
, I've maked a function named init
that must render a "component".
Inside the render
function I make a new instance of NavigatieButton
using code below:
var navBtn = new NavigatieButton('0 0 0');
But if I call init
, the properties location
, rotation
and navigatie
are undefined.
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 2: I'm using aframe to create WebVR.
Instead of
var comp = NavigatieButton.prototype.init();
you must call .init()
with the object you just created:
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.
You are calling init function of NavigatieButton
constructor directly which is not a newly created object.
Use navBtn.init();
instead of NavigatieButton.prototype.init();
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.