js是面向对象编程的,对象的创建方式不止一种,下面我们来看一下,它的对象的几种创建方式。
一种是通过object直接创建对象,然后可以给对象增加属性和函数。因为object类是所有javascript类的基类,提供了一种创建自定义对象的简单方式,不需要再定义构造函数。主要属性:
constuctor-对象的构造函数
prototype-获得类的prototype对象.static性质
这是一个使用object创建对象的方式。
<html>
<head>
<script language="javascript">
var person = new Object();//通过object直接创建对象
person.name = "haha";
</script>
</head>
<body>
</body>
</html>
下面是一个使用prototype为原型对象增加属性和函数的方式,代码为:
<html>
<head>
<script language="javascript">
var p1 = new Object();
p1.name = "haha";
var p2 = new Object();
p2.name = "lala";
Object.prototype.age = 10;
Object.prototype.test = function(){window.alert("test");}
window.alert(p1.name);
window.alert("p1:" + p1.age);
p1.test();
window.alert(p2.name);
window.alert("p2:" + p2.age);
p2.test();
</script>
</head>
<body>
</body>
</html>
同样也可以自己创建原型对象。代码为:
<html>
<head>
<script language="javascript">
function Person() {};
var p1 = new Person();
p1.name = "拉拉";
window.alert(p1.name);
var al = "na" + "me";
window.alert(p1[al]);
</script>
</head>
<body>
</body>
</html>
可以在创建对象时候就为对象设定属性和方法,代码如下:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" language="javascript">
function jiSuan(num1, num2, oper) {
if(oper == "+") {
return num1 + num2;
}
else if(oper == "-") {
return num1 - num2;
}
else if(oper == "*") {
return num1 * num2;
}
else if(oper == "/") {
return num1 / num2;
}
}
function Person(name, age, fun) {
this.name = name;
this.age = age;
this.myfun = fun;
}
var p1 = new Person("aa", 9, jiSuan);
window.alert(p1.name);
window.alert(p1.myfun(3, 5, "+"));
</script>
</head>
<body>
</body>
</html>
还有一点说明,先看代码:
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script type="text/javascript" language="javascript">
var dog = {name: dog};
function test() {
window.alert(this.name);
}
test();
window.test();
test.call(dog);//等价于dog.test();
</script>
</head>
<body>
</body>
</html>
在这段代码中,标明this代表传入的对象,这样我们把dog传入,this就代表dog。
js中的函数:
js中不支持函数的重载。
结论:js在调用一个函数的时候,是根据函数名来调用,如果有多个函数名相同,则调用最后那个函数。