JavaScript中的OOPS概念是什么?
很多时候,变量或数组不足以模拟真实情况。如果对象是一个家,它将拥有一些属性,如房间数量、油漆颜色、位置等,以及方法,如culateArea、changeOwner等。
如何创建对象
可以创建如下对象:
var objName = new Object();
objName.property1 = value1;
objName.property2 = value2;
objName.method1 = function()
{
line of code
}
或
访问对象属性和方法
可以按如下方式访问对象的属性:
可以像这样访问对象的方法:
可以自己尝试此示例:
<html>
<head>
<title>
Objects!!!
</title>
<script type="text/javascript">
var student = new Object();
student.fName = "John";
student.lName = "Smith";
student.id = 5;
student.markE = 76;
student.markM = 99;
student.markS = 87;
student.calculateAverage = function()
{
return (student.markE + student.markM + student.markS)/3;
};
student.displayDetails = function()
{
document.write("Student Id: " + student.id + "<br />");
document.write("Name: " + student.fName + " " + student.lName + "<br />");
var avg = student.calculateAverage();
document.write("Average Marks: " + avg);
};
student.displayDetails();
</script>
</head>
<body>
</body>
</html>
OOPS构造函数
但是创建这种对象没有什么用处,因为在这里,还必须为不同的学生创建不同的对象。对象构造函数帮助创建可重用的对象类型,以满足单个实例的需要。
可以自己尝试此示例:
<html>
<head>
<script type="text/javascript">
function Student(first, last, id, english, maths, science)
{
this.fName = first;
this.lName = last;
this.id = id;
this.markE = english;
this.markM = maths;
this.markS = science;
this.calculateAverage = function()
{
return (this.markE + this.markM + this.markS)/3;
}
this.displayDetails = function()
{
document.write("Student Id: " + this.id + "<br />");
document.write("Name: " + this.fName + " " + this.lName + "<br />");
var avg = this.calculateAverage();
document.write("Average Marks: " + avg + "<br /><br />");
}
}
var st1 = new Student("John", "Smith", 15, 85, 79, 90);
var st2 = new Student("Hannah", "Turner", 23, 75, 80, 82);
var st3 = new Student("Kevin", "White", 4, 93, 89, 90);
var st4 = new Student("Rose", "Taylor", 11, 55, 63, 45);
st1.displayDetails();
st2.displayDetails();
st3.displayDetails();
st4.displayDetails();
</script>
</head>
<body>
</body>
</html>
循环访问对象的属性
语法:
循环中的for/in通常用于遍历对象的属性。可以为变量指定任何名称,但是对象的名称应该与需要遍历的现有对象的名称相同。
可以自己尝试此示例:
<html>
<head>
<script type="text/javascript">
var employee={first:"John", last:"Doe", department:"Accounts"};
var details = "";
document.write("<b>Using for/in loops </b><br />");
for (var x in employee)
{
details = x + ": " + employee[x];
document.write(details + "<br />");
}
</script>
</head>
<body>
</body>
</html>