JavaScript中通过prototype属性共享属性和方法的技巧实例
具体代码如下:
//定义函数 functionpeople(name,sex,age){ this.name=name; this.sex=sex; this.age=age; } //共享isStudent与sayName方法 people.prototype={ isStudent:true, sayName:function(){ alert(this.name); } } varpeople1=newpeople('韩梅梅','女',16); //实例化对象1 varpeople2=newpeople('李磊','男',17); //实例化对象2 //通过共享的方法让两个对象说出自己的名字 people1.sayName(); people2.sayName(); //通过共享的参数判断他们都是学生 if(people1.isStudent==people2.isStudent)alert('他们都是学生');
本文也提到了一些javascript对象的相关知识,应该不难理解。如果实在不明白的话可以稍微百度一下。