Dan*_*nny 10 javascript class object
我一直想尝试javascript一段时间,但我希望它是"面向对象的"所以我试图在不同的文件中创建不同的javascript类并尝试创建一个对象并在不同的文件中调用它的方法功能,但它似乎不起作用.
这是我到目前为止:
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;
}
}
Run Code Online (Sandbox Code Playgroud)
function Job(title)
{
this.title = title;
this.description;
this.setDescription = function(description)
{
this.description = description;
}
}
Run Code Online (Sandbox Code Playgroud)
function main()
{
var employee = new Person("Richard", 23, male);
document.getElementById("mainBody").innerHTML = employee.getName();
}
Run Code Online (Sandbox Code Playgroud)
<!DOCTYPE HTML>
<HTML>
<head>
<title>javascript test</title>
<script src="main.js" type="javascript"></script>
</head>
<body>
<p id="mainBody"></p>
</body>
</HTML>
Run Code Online (Sandbox Code Playgroud)
任何帮助或建议将不胜感激.
非常感谢
编辑:非常感谢所有的答案和建议,但是,我已经包括了我的所有javascript文件,但它仍然无法正常工作...
Min*_*hev 17
目前,JavaScript并不够聪明,无需帮助即可找到您的依赖项.
你需要:
<!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>
Run Code Online (Sandbox Code Playgroud)
注意:
如果您希望按需加载依赖项,则可以将AMD(异步模块定义)与requirejs或其他内容一起使用.
使用AMD,您可以定义如下内容:
define(['Job', 'person'], function (job, person) {
//Define the module value by returning a value.
return function () {};
});
Run Code Online (Sandbox Code Playgroud)
define方法接受两个参数:依赖项和定义模块的函数.当加载所有依赖项时,它们作为参数传递给函数,其中是模块定义.
还有一点需要注意的是,Person而Job不是课程.它们只是函数(构造函数),它们根据定义中的规则生成对象.