Hi
Sorry I am not sure if this a correctly formulated question, but I wonder if it is possible to put instances of an object (like myFather here) in a separate function. The code I show is not working, it is an example from w3schools, but it demonstrates the best what I would like to achieve:

<script>
function person(firstname,lastname,age,eyecolor)
{
this.firstname=firstname;
this.lastname=lastname;
this.age=age;
this.eyecolor=eyecolor;
}
function(){
myFather2=new person("John","Doe",50,"blue");
document.write(myFather2.firstname + " is " + myFather2.age + " years old.");
}
document.write(myFather.firstname + " is " + myFather.age + " years old.");
</script>

I could take any suggestions regarding if it actually makes sense at all to do that, as obviously I would like properties of myFather (name, age) to be available throughout the code. I am new to js, so please excuse me; I've been trying to find an answer to it over the web, but with no success.

Recommended Answers

All 6 Replies

Hmm... You don't need to have function() to create an object unless you are going to init it later on inside another function or let a function init a new class object. Simply create it (and must be) after the constructor function.

<script type="text/javascript">
function person(firstname,lastname,age,eyecolor) {
  this.firstname=firstname;
  this.lastname=lastname;
  this.age=age;
  this.eyecolor=eyecolor;
}

// should declare a variable with "var" for the safe side
var myFather2=new person("John","Doe",50,"blue");
document.write(myFather2.firstname + " is " + myFather2.age + " years old.");
</script>

Ok thank you. I wasn't actually sure if it is ok that 'myFather' (and more instances of Person) remains global.

Yes, once the constructor function is declared, as long as it is declared on the top of the page (prefer inside the head tag), it remains global to the rest of the page.

Hmmm I call all my js from the external file - it is better. And I try to avoid globals, that is the base of my question....

External file is similar to declaring your function in the head tag. The only advantage of external file is that it can be reused in other pages. The cleaner page is a side effect of not having all scripts in your page. If you look at the DOM, they all are inside it anyway.

Global variables have their use and purposes. It is better to not having globals at all, but that does not mean you should not have them at all. You may not see its purpose for now, but keep in mind that you may need one in the future for certain purposes. That's all I can tell you.

Hah thank you my Cryptic Saviour :)

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.