I wrote a script, which creates 3 objects. The constructor has a local variable mushroomsCount:
Mushroom = function(num) {
var mushroomsCount = 0;
this.id = num;
this.Create();
}
Mushroom.prototype.Create = function() {
this.mushroomsCount++;
}
Mushroom.prototype.Display = function() {
console.log('mushromms count total is: ' + Mushroom.mushroomsCount);
}
$(document).ready(function() {
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display(); // first way
Mushroom.Display(); // second way
});
after creating the objects, I try to display the number of the objects at Mushroom.prototype.Display(), but I'm getting undefined.
codepen
You can use a property on Mushroom itselft (like you already had, but not had accessed).
function Mushroom(num) {
this.id = num;
this.create();
}
Mushroom.mushroomCount = 0; // this is public!
Mushroom.prototype.create = function () {
Mushroom.mushroomCount++;
}
Mushroom.prototype.display = function () {
document.write('mushromms count total is: ' + Mushroom.mushroomCount + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Or use a closure with an IIFE:
var Mushroom = function () {
var mushroomCount = 0;
var f = function (num) {
this.id = num;
this.create();
};
f.prototype.create = function () { mushroomCount++; }
f.prototype.display = function () { document.write('mushromms count total is: ' + mushroomCount + '<br>'); }
return f;
}();
var mushroom = [new Mushroom(0), new Mushroom(1), new Mushroom(2)];
mushroom[0].display();
mushroom[1].display();
mushroom[2].display();
Simple count instances of Mushroom 'class':
function Mushroom(num) {
this.id = num;
Mushroom.count++;
}
Mushroom.count = 0;
Mushroom.prototype.Display = function () {
document.write('mushromms count total is: ' + Mushroom.count + '<br>');
}
var mushroom = [];
mushroom[0] = new Mushroom(0);
mushroom[1] = new Mushroom(1);
mushroom[2] = new Mushroom(2);
mushroom[2].Display();
Related
So the script is really simple, I try to push the dNumber into variable pattern and the results are always "underfined".
when i try to do the same with just push a TEXT for example it's worked.
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber() {
var a = Math.floor((Math.random() * 100 / 25) + 1);
console.log(a);
console.log(pattern);
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
pattern.push(x);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber(){
var a = Math.floor((Math.random()*100/25)+1);
console.log(a);
console.log(pattern);
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
// pattern.push("alex"); this is work!
pattern.push(x);
pattern.push(dNumber());
//this isn't work what should be number looks like appear as underfined.
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You need to return a from dNumber function so that you can use :)
var level = 0;
var pattern = [];
var userPatern = [];
function dNumber() {
var a = Math.floor((Math.random() * 100 / 25) + 1);
console.log(a);
console.log(pattern);
// return a here if not then it's gonna return undefined by default :)
return a;
}
$("body").click(gamestart);
$("body").keypress(gamestart);
function gamestart() {
$("#level-title").text("level " + level);
var x = dNumber();
pattern.push(x);
console.log(pattern);
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
I defined a JavaScript function using a custom service and I called this function using the service in my controller. This function uses two parameters: The first one is input which I am getting by hitting the below API and the second one is the value of the year which I'm getting using ng-model directive. When I am calling this function in my controller I am getting an error like type is not defined or id is not defined etc. Is it the right way to call a JavaScript function in the controller. Please suggest me.
$http.get("http://152.144.218.70:8080/USACrime/api/crimeMultiple?city=" +$scope.strCity + "&crime=" + $scope.type1 + "&model=" + model).success(function (result) {
$scope.prograssing = false;
console.log("manisha", $scope.strCity);
console.log("kanika", result);
$scope.output = result;
console.log("monga", $scope.output);
$scope.hex = hexafy.year_city($scope.output,$scope.type);
console.log("service", $scope.hex);
});
myapp.js
var app= angular.module("myApp",["ngRoute","leaflet-directive","pb.ds.components"]);
var geomarker = new L.FeatureGroup();
app.service('hexafy', function() {
this.year_city = function (input2,years) {
if(years.toLowerCase()=="all"){
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] =outerBoundary;
themes = [];
for(var i in input){
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for(var j in input[i]["prediction"]){
dict = {};
if(yrs.indexOf(input[i]["prediction"][j]["year"])>-1){
dict["name"] = input[i]["prediction"][j]["year"]+" "+input[i]["crime"]+" Crime";
dict["description"] = input[i]["crime"]+" Crime for "+input[i]["prediction"][j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase()+"CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]',crimeThemeValue["individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes",JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
};
});
});
1) .success and .error methods are deprecated and it is not good to go with it. Instead you'd better use .then(successCallback, errorCallback)
2) To use a service method the proper way is to it like this:
app.service('myService', function() {
var service = {
method:method
};
return service;
function method() {
//Logic
}
})
So in your case the way to go is:
app.service('hexafy', function () {
return {
years_city: function (input2, years) {
if (years.toLowerCase() == "all") {
years = "2012,2013,2014,2015,2016,2017,2018,2019";
}
var yrs = years.split(",");
output = {};
outerBoundary = {};
boundary = {};
boundary["boundaryId"] = input[0]["id"];
boundary["boundaryType"] = input[0]["type"];
boundary["boundaryRef"] = "C1";
outerBoundary["boundary"] = boundary;
output["boundaries"] = outerBoundary;
themes = [];
for (var i in input) {
crimeTheme = {};
crimeThemeValue = {};
crimeThemeValue["boundaryRef"] = "C1";
result = [];
for (var j in input[i]["prediction"]) {
dict = {};
if (yrs.indexOf(input[i]["prediction"][j]["year"]) > -1) {
dict["name"] = input[i]["prediction"][j]["year"] + " " + input[i]["crime"] +
" Crime";
dict["description"] = input[i]["crime"] + " Crime for " + input[i]["prediction"]
[j]["year"];
dict["value"] = input[i]["prediction"][j]["count"];
dict["accuracy"] = input[i]["accuracy"];
result.push(dict);
}
}
crime = input[i]["crime"].toLowerCase() + "CrimeTheme";
crimeThemeValue["individualValueVariable"] = result;
console.log('crimeThemeValue["individualValueVariable"]', crimeThemeValue[
"individualValueVariable"]);
crimeTheme[crime] = crimeThemeValue;
themes.push(crimeTheme);
console.log("themes", JSON.stringify(themes));
}
output["themes"] = themes;
console.log(output);
return output;
}
}
})
I am using the method of a javascript object to create HTML to write that object.
Within that method I have a date (in string format as a SQL Date) which I format to dd MMM YYYY in an external method. The external method works fine returning the string I need, but when I set the variable within my object's method it is returned as undefined.
Hereby the relevant code:
function CreateReview(reviewID, visitDate) {
var reviewObject = {
iD: reviewID,
visitDate: visitDate,
CreateReviewObject : function(c) {
var reviewContainer = document.createElement('div');
reviewContainer.id = 'Review_' + this.iD;
reviewContainer.className = 'Card Review';
var headerDIV = document.createElement('div');
headerDIV.className = 'Header';
var dateTagsDIV = document.createElement('div');
dateTagsDIV.className = 'DateTags';
var datesDIV = document.createElement('div');
datesDIV.className = 'Dates';
var formattedVisitDate = getFormattedDate(this.visitDate);
console.log(formattedVisitDate);
var dateDIV = document.createElement('div');
dateDIV.className = 'Date';
dateDIV.innerHTML = formattedVisitDate;
datesDIV.appendChild(dateDIV);
dateTagsDIV.appendChild(datesDIV);
headerDIV.appendChild(dateTagsDIV);
reviewContainer.appendChild(headerDIV);
return reviewContainer;
}
};
return reviewObject;
}
function getFormattedDate(input) {
input = input.replace(/-/g,'/');
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
p2 = parseInt(p2);
p3 = parseInt(p3);
var months = ['jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'];
var date = (p3<10?"0"+p3:p3) + " " + months[parseInt(p2-1)] + " " + p1;
console.log(date);
return date;
});
}
The output of the console in getFormattedDate is then
12 mei 2015
While in CreateReview it is
undefined
I have tried the following way as well:
function CreateReview(reviewID, restaurant, kitchenTypes, tags, pictures, ratings, thumbPicture, visitDate, introduction, description) {
var reviewObject = {
iD: reviewID,
visitDate: visitDate,
CreateReviewObject : function(c) {
var getFormattedVisitDate = function(visitDate) {
return function() { getFormattedDate(visitDate); };
};
var reviewContainer = document.createElement('div');
reviewContainer.id = 'Review_' + this.iD;
reviewContainer.className = 'Card Review';
var headerDIV = document.createElement('div');
headerDIV.className = 'Header';
var dateTagsDIV = document.createElement('div');
dateTagsDIV.className = 'DateTags';
var datesDIV = document.createElement('div');
datesDIV.className = 'Dates';
var formattedVisitDate = getFormattedVisitDate(this.visitDate);
console.log(formattedVisitDate);
var dateDIV = document.createElement('div');
dateDIV.className = 'Date';
dateDIV.innerHTML = formattedVisitDate;
datesDIV.appendChild(dateDIV);
dateTagsDIV.appendChild(datesDIV);
headerDIV.appendChild(dateTagsDIV);
reviewContainer.appendChild(headerDIV);
return reviewContainer;
}
};
return reviewObject;
}
function getFormattedDate(input) {
input = input.replace(/-/g,'/');
var pattern = /(.*?)\/(.*?)\/(.*?)$/;
var result = input.replace(pattern,function(match,p1,p2,p3){
p2 = parseInt(p2);
p3 = parseInt(p3);
var months = ['jan','feb','maa','apr','mei','jun','jul','aug','sep','okt','nov','dec'];
var date = (p3<10?"0"+p3:p3) + " " + months[parseInt(p2-1)] + " " + p1;
console.log(date);
return date;
});
}
Which gives me this output in in CreateReview:
return function() { getFormattedDate(visitDate); };
Why does the CreateReview call return undefined when the console does not?
In your function getFormattedDate(), you have
var result = input.replace(pattern, function(match,p1,p2,p3) {... return date; });
so result contains the returned value of the replace function, but getFormattedDate doesn't return anything ==> undefined when called from CreateReview.
Add return result; at the end of the function getFormattedDate.
I am unable to access NatArray[ ] in the second function, and u4count in the second function is coming as 0. What may be the reason?
<script type="text/javascript">
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1()
{
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check()
{
alert("coming here" + u4count + "natentry" + NatArray[0] );
}
</script>
Thanks in Advance
Works for me as excpected. The order you call your functions is important in this case:
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1() {
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check() {
alert("coming here " + u4count + " natentry " + NatArray[0]);
}
Check1();
Check();
As some answering users figured out is the unclosed inline comment bad but not the reason for your problem. Something about comments in inline-code
http://fiddle.jshell.net/r8sKf/
You can call this 2 functions in window.onload so it will call second function and also alert and NatArray[ ] value inside alert.
Try something like this:
var NatArray = [];
var NatArrayloc = [];
var u4count = 0;
function Check1() {
NatArray[0] = 202116108;
NatArrayloc[0] = 202116109;
NatArray[1] = 202116111;
NatArrayloc[1] = 202116112;
NatArray[2] = 202116113;
NatArrayloc[2] = 202116114;
u4count = 3;
}
function Check() {
alert("coming here " + u4count + " natentry " + NatArray[0]);
}
window.onload=function(){
Check1();
Check();
};
Here you go:
http://jsfiddle.net/R23eD/
You need to remove the <!-- from your script start. And you're also not calling the Check1() function to initialize the values
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Constructors in Javascript objects
im trying to learn how to create class's in javascript. I found that is very diffuclt for me to understand it.
now, i want to know if is possible to create a constractor in javascript, like we can do in c# or other programming languages.
i tried few things:
way 1:
function SiteProfile(_url) {
this.url = "";
this.name = this.ExtractNameFromURL();
}
SiteProfile.prototype.ExtractNameFromURL = function () {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
way 2:
function Site() {
this.url = "";
this.name = "";
this.Site = function (_url) {
this.url = _url;
this.name = this.ExtractNameFromURL();
}
this.ExtractNameFromURL = function () {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
}
both of class's should take a URL, and just get the name from him with out the www. or the .com
i want to know if i can design a class, that i can create an instance like so:
var site = new SiteProfile("www.google.co.il");
document.write(site.name); // becuse, this do nothing
(sorry for my english)
You're real close. The problem with your first form is simply that you are not setting the url property with the _url parameter.
function SiteProfile(_url) {
//change the line below to:
//this.url = _url;
this.url = "";
this.name = this.ExtractNameFromURL();
}
SiteProfile.prototype.ExtractNameFromURL = function() {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
}
var site = new SiteProfile("www.google.co.il");
document.write(site.name); // with the change above, this will behave as expected
Here's the fiddle for the first form: http://jsfiddle.net/BCnfx/
The problem with the second form is two-fold. The main function should be called "SiteProfile" if you still want to instantiate it as such. The second problem is that you need to initialize the url property by passing in the url to the Site method.
//function below should be called "SiteProfile", not "Site"
function Site() {
this.url = "";
this.name = "";
this.Site = function(_url) {
this.url = _url;
this.name = this.ExtractNameFromURL();
};
this.ExtractNameFromURL = function() {
var firstDOT = this.url.indexOf(".");
var secondDOT = this.url.indexOf(".", firstDOT + 1);
var theName = "";
for (var i = firstDOT + 1; i < secondDOT; i++) {
theName += this.url[i];
}
return theName;
};
}
//now instantiate like this instead.
var site = new SiteProfile();
site.Site("www.google.co.il");
document.write(site.name); // with the changes above, this will behave as expected
Here's the fiddle for the second form: http://jsfiddle.net/BCnfx/1/
in your first example:
function SiteProfile(_url) {
this.url = _url;
this.name = this.ExtractNameFromURL();
}
then you will be able to do :
var site = new SiteProfile("www.google.co.il");
document.write(site.name);