js创建对象的几种方式和函数说明

         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在调用一个函数的时候,是根据函数名来调用,如果有多个函数名相同,则调用最后那个函数。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值