I've been trying to do javascript for sometime now, but i want it to be "object-orientated" so I'm trying to create different javascript classes in different files and try to create an object and call it's methods in a different file function, but it doesn't seem to work.
This is what I have so far:
person.js
function Person(name, age, gender)
{
this.age = age;
this.name = name;
this.gender = gender;
this.job;
this.setJob = function(job)
{
this.job = job;
}
this.getAge = function()
{
return this.age;
}
this.getName = function()
{
return this.name;
}
this.getGender = function()
{
return this.gender;
}
}
Job.js
function Job(title)
{
this.title = title;
this.description;
this.setDescription = function(description)
{
this.description = description;
}
}
main.js
function main()
{
var employee = new Person("Richard", 23, male);
document.getElementById("mainBody").innerHTML = employee.getName();
}
index.html
<!DOCTYPE HTML>
<HTML>
<head>
<title>javascript test</title>
<script src="main.js" type="javascript"></script>
</head>
<body>
<p id="mainBody"></p>
</body>
</HTML>
any help or advice would be greatly appreciated.
Many thanks
EDIT:
Many thanks for all the answers and suggestions, however, I've included all my javascript files and still it doesn't work...
Currently JavaScript is not clever enough to find your dependencies without help.
You need:
<!DOCTYPE HTML>
<HTML>
<head>
<title>javascript test</title>
<script src="person.js" type="javascript"></script>
<script src="Job.js" type="javascript"></script>
<script src="main.js" type="javascript"></script>
</head>
<body>
<p id="mainBody"></p>
</body>
</HTML>
Note:
If you want on-demand load of the dependencies then you can use AMD (Asynchronous Module Definition) with requirejs or something else.
Using AMD you can define something like:
define(['Job', 'person'], function (job, person) {
//Define the module value by returning a value.
return function () {};
});
The define method accepts two arguments: dependencies and function which defines the module.
When all dependencies are loaded they are passed as arguments to the function where is the module definition.
One more thing to notice is that Person and Job are not classes. They are just functions (constructor functions) which produces objects based on rules in their definitions.
Files aren't automatically loaded, you need to add each .js file to the document with script tags and in the right order as well, otherwise you will get errors.
You might want to look into requirejs.org for dependency management, it's the hawtest thing lately untill ES6 becomes mainstream anyways.
class methods should be defined via prototype so they receive 'this' reference,
like that:
Person.prototype.getGender = function()
{
return this.gender;
};
you can try to include the 1st and 2nd javascript files first.
like:
<!DOCTYPE HTML>
<HTML>
<head>
<title>javascript test</title>
<script src="person.js" type="javascript"></script>
<script src="Job.js" type="javascript"></script>
<script src="main.js" type="javascript"></script>
</head>
<body>
<p id="mainBody"></p>
</body>
</HTML>
You need to return the object created by Person in order for it to constitute a new instance of the Person prototype.
return(this);
This isn't working because, according to your HTML code, the browser is only loading main.js
<script src="main.js" type="javascript"></script>
Since Javascript runs in the browser, not on the server where the other files are, the browser will try to execute main.js and fail, since it doesn't have access to the classes in the other files. If you include each one of the files (making sure that every file is included after the one it requires), you should have more success.
For example:
<script src="Job.js" type="javascript"></script>
<script src="person.js" type="javascript"></script>
<script src="main.js" type="javascript"></script>
I see three issues with the code.
The page does not import the proper external Javascript files
<head>
<title>javascript test</title>
<script src="job.js" type="javascript"></script>
<script src="person.js" type="javascript"></script>
<script src="main.js" type="javascript"></script>
</head>
Male needs to be a String literal
When the interpreter encounters male within the Person constructor it looks for a variable, which it cannot find.
function main()
{
var employee = new Person("Richard", 23, "male");
document.getElementById("mainBody").innerHTML = employee.getName();
}
The code should call the main function.
Without a call to the main function the code is never kicked off.
function main()
{
var employee = new Person("Richard", 23, "male");
document.getElementById("mainBody").innerHTML = employee.getName();
}
main();
Working Example: http://jsfiddle.net/R7Ybn/
ES6: https://www.sitepoint.com/understanding-es6-modules/
Supported in Safari as of Summer of 2017, but no support in other browsers. In a year or so, it seems like it'll be supported by Edge, Firefox, Chrome, Opera, and safari. So keep it in mind?
https://caniuse.com/#feat=es6-module
I was having a similar issue and the problem for me stemmed from writing
"script src="Person.js" type="javascript"
instead of
"script src="Person.js" type="text/javascript"
in my index.html file
Hope this Helps,
Related
I have a JavaScript module mymmodule.js exporting a list:
export var mylist = ['Hallo', 'duda'];
Normally this module is used in other modules and this works fine. But additionally I want to use the export(s) of the module as-is in an inline script on an HTML page. I tried to copy the exports to the window object:
<html>
<head>
<script type="module">import * as mm from './mymodule.js'; window.mm = mm;</script>
</head>
<h1>MyMain</h1>
<p>
<div id = "info">...</div>
</p>
<script type="text/javascript">
document.getElementById('info').textContent = window.mm.mylist;
</script>
</html>
but I get the error "window.mm is undefined" in the console. I tried referencing mm.mylist instead of window.mm.mylist with no better result.
How can I reference the exports of a module in a second inline script on the HTML page?
The problem is that modules are execute at the same stage as pscripts with the defer attribute](https://javascript.info/script-async-defer#defer), i.e. after reading the page and executing JavaScript in script tags.
Therefore, when the browser sees
document.getElementById('info').textContent = mm.mylist
the mymodule.js script hasn't been executed and the mm object is not available yet.
To mitigate this you need to run code referencing exports from mymodule after the DOM is completely loaded, e.g. in the onload event:
<html>
<head>
<script type="module">import * as mm from './mymodule.js'; window.mm = mm;</script>
</head>
<h1>MyMain</h1>
<p>
<div id = "info">...</div>
</p>
<script type="text/javascript">
window.onload = function() {
document.getElementById('info').textContent = mm.mylist;
}
</script>
</html>
I am trying to access a var one file from another file. Here is what I have:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="btn">Global</button>
<script src="/test.js"></script>
<script src="/testpass.js"></script>
</body>
</html>
test.js:
export var globalVariable = {
output: "test this"
};
testpass.js:
import { globalVariable } from './test.js'
document.getElementById("btn").addEventListener("click", function(){
alert(globalVariable.output);
});
Nothing happens. I also tried doing
var globalVariable = {
output: "test this"
};
and then simply accessing it from another file as demonstrated in this answer:
Call variables from one javascript file to another but it did not work. Tried exporting it as mentioned in this answer: Can I access variables from another file? as well but no success. I am using sublime text and vue.js and it does not work for both of them.
In addition if I do something like this:
import { globalVariable } from '.test.js'
document.getElementById("btn").addEventListener("click", function(){
alert("Not printing the globalVariable here");
});
the entire javascript file seems to fail and doesn't work at all when called in the HTML file.
You should be getting an error from the browser's JavaScript engine in the web console. To use import and export, you have to treat your code as a module. Your script tags don't, they treat the code as just script. To treat testpass.js as a module, you must use type="module":
<script src="/testpass.js" type="module"></script>
No need to list test.js, testpass.js will load it. So:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="btn">Global</button>
<script src="/testpass.js" type="module"></script>
</body>
</html>
Sadly, we can't show modules in SO's Stack Snippets, but if you make those changes, this codesandbox example is what you end up with (except I changed src="/testpass.js" to src="./testpass.js").
Note that globalVariable isn't a global variable (which is a Good Thing™). It's a local variable within test.js that it exports. Any other module can import it, but it's not a global.
I have two javascript files and one html page. i want to include a js file to another js file but i dont know how to include js file to another one.
anyone can please help me?
following is my code
html code:
<html lang="en">
<head>
<script src="main.js" ></script>
</head>
<body onload="show()">
</body> </head>
</html>
following are the javascript files:
1.js
var x=10;
function show()
{
setvalue(x)
}
2.js
var D=;
function setvalue(x)
{
D = x;
alert(D);
}
if it's just a matter of accessing the functions and objects in the first javascript file just do something like this:
<script src="main1.js"></script>
<script src="main2.js"></script>
this way any function in main1.js will be available in main2.js
I am trying to set up a backbone driven web application but cannot get Backbone to load correctly. I get two errors when I load the required files:
-Uncaught ReferenceError: Backbone is not defined test.html: 17
-Uncaught TypeError: Cannot read property 'each' of undefined backbone.min.js: 1
I have tried multiple sources for the backbone, underscore and jquery files and am still having the same errors. Any help would be appreciated. Thanks.
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="backbone-min.js"></script>
<script "text/javascript" src="jquery-2.1.1.js"></script>
<script "text/javascript" src="underscore-min.js"></script>
<script>
Person = Backbone.Model.extend({
initialize: function(){
console.log("hello world");
}
});
var person = new Person();
</script>
</body>
</html>
You must include your libraries properly to fulfill missing dependencies:
<script src="jquery-2.1.1.min.js"></script>
<script src="underscore-min.js"></script>
<script src="backbone-min.js"></script>
It's important to include underscore before you include backbone because underscore is a dependency of backbone.
include Backbone.js and Underscore.js(a dependency of Backbone.js)
Related introduction on backbone.
This is a common mistake with common libraries such as jQuery, wherea libraries like Bootstrap rely on components provided by an external provider.
A quick glance and I can't see anything immediately wrong, although you are missing the 'type' on your second and third script tags. When you run the page in browser, are there any errors logged out to the console, can you see the libraries being loaded fine in the network viewer too? My immediate hunch would be the source paths are wrong and so the libraries aren't being loaded.
Dependencies!!! The order matters, backbone needs jQuery and underscore
<html>
<head>
<title></title>
</head>
<body>
<script type="text/javascript" src="jquery-2.1.1.min.js"></script>
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript" src="backbone-min.js"></script>
<script>
Person = Backbone.Model.extend({
initialize: function(){
console.log("hello world");
}
});
var person = new Person();
</script>
</body>
I refer [https://github.com/olark/lightningjs] to load the js in separate window namespace .
I have tested a script file named as sample.js like below need to be load in separate window namespace.
function testjs(){
console.log("sample");
}
I include the lightningjs-embed.js and lightining-bootstrap.js in my html.
<html>
<head>
<title>testing light js</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/lightningjs-master/lightningjs-embed.js" ></script>
<script type="text/javascript" src="js/lightningjs-master/lightningjs-bootstrap.js"></script>
<script type="text/javascript">/*{literal}<![CDATA[*/
/*** lightningjs-embed.min.js ***/
window.piratelib = lightningjs.require("piratelib","js/sample.js");
/*]]>{/literal}*/</script>
console.log("modules",lightningjs.modules);
piratelib("testjs");
In console i can view two objects one as lightningjs another one as piratelib. I am expecting to get "sample" in console after calling piratelib("testjs"). But am not getting sample in the console. If try piratelib("testjs") in console it shows
function promiseFunction() {
console.log("promisdeId",promiseResponseId);
promiseFunction.id = promiseResponseId;
return modules[namespace].apply(promiseFunction, arguments)
}
instead of actual function in sample.js
function testjs(){
console.log("sample");
}
Suggest me some ideas to load js under separate window.namespace in order to avoid to js conflict. Clarify me if am calling functions in right way using lightningjs.
Thanks in advance.
The functions handled by LightningJS return promises, so:
piratelib("testjs").then(function(result) {
console.log(result);
}, function(error) {
// Handle your error
});