saber 酱的抱枕

Fly me to the moon

04/20
2015
学习

javascript创建对象

我们要创建两个“人”的对象,并且设置每个人的属性。

<table border="1">
	<tr>
		<td>名字</td>
		<td>性别</td>
		<td>年龄</td>
		<td>喜欢</td>
		<td>身高</td>
	</tr>
	<script type="text/javascript">
		function creatMan (名字,性别,年龄,喜欢) {
			this.名字=名字;
			this.性别=性别;
			this.年龄=年龄;
			this.喜欢=喜欢;
		}
		var Saber=new creatMan('Saber','女',154,'士狼');
		var Illya=new creatMan('Illya','女',150,'士狼');

		creatMan.prototype.height = function  (height) {
			this.height=height+'cm';
		}
		Saber.height(154);
		Illya.height(150);

		document.write('<tr>')
			for(attr in Saber){
				document.write('<td>'+ Saber[attr] +'</td>')
			}
		document.write('</tr>')
		document.write('<tr>')
			for(attr in Illya){
				document.write('<td>'+ Illya[attr] +'</td>')
			}
		document.write('</tr>')
	</script>
</table>

输出如下:
js创建对象
这种创建对象的方式在w3c里称为“混合的构造函数/原型方式”,使用构造函数来完成对象的创建,并在函数中使用this来设置对象的属性,this指代当前对象。
身高这块是使用prototype追加了一个方法,在这个方法里设置了身高属性。一旦对构造函数使用prototype追加属性,则每个由该函数创建的对象也都有了该属性,即使未赋值。如果未赋值,则追加值为等号右边内容(如果右边是函数,即是函数的源代码)。
不需要对此构造函数产生的每个对象都追加属性时,用普通方法为单个对象赋值就可以了:

Saber.height='154cm';

查看w3c页面:ECMAScript 定义类或对象

javascript创建对象