The code is here:
Father.js
(function(){
function father(){
};
father.prototype.init = function(){
console.log('father');
}
})()
Child.js
(function(){
function child(){
}
child.prototype.init = function(){
console.log('child');
}
var father = new father();
})()
I have 2 questions: How can I call father object or child object between script tag or any third javascript files that I create ? Second: how can I call the father object inside child class. I am new to JS and have some problems with OOP in javascript. Thank you very much for your help
3 Answers 3
You should assign the result of the anonymous function to a variable that way you can use it without leaking what's inside of the IIFE (Immediately Invoked Function Expression), thus encapsulating everything but the constructor:
var Father = (function(){
// Private stuff...
function Father(){}
Father.prototype.something = function(){};
return Father; // Public constructor
}());
Now you can use Father in your Child class, or better yet, use the same pattern but pass the parent class as parameter to the IIFE:
var Child = (function(_parent){
function Child() {
_parent.apply(this, arguments); // inherit properties from Parent class
}
Child.prototype = Object.create(_parent.prototype); // inherit Parent prototype
Child.prototype.something = function(){};
return Child;
}(Father));
2 Comments
this.constructor at some point in Child intances.Answer to question one is you define father and child in the global scope:
function father(){
};
father.prototype.init = function(){
console.log('father');
}
function child(){
}
child.prototype.init = function(){
console.log('child');
}
// can't name your var father because it'll overwrite the father function
var dad = new father();
You can use namespacing to restrict the amounts of variables in the global scope:
in father.js:
var myApp=myApp || {};
myApp.father=...
in child.js:
var myApp=myApp || {};
myApp.child=...
var dad = new myApp.father();
To call father object in child you can do father.call(this); making all the father properies in the father function defined as this.someprop=... part of the just created child. If you just want to access the father instance named dad (see code above) then you can do dad.init()
More on inheritance and prototype here:
I've set up a fiddle : http://jsfiddle.net/J75Zz/
It doesn't matter on how many .js files you "distribute" your code, it's just "one code block", which get's executed (well, almost ...).
You should name Objects with Capitals, there's already a clash between object father and variable father.
var Father = (function(){...; return Father }());