JavaScript中通过prototype属性共享属性和方法的技巧实例

  作者:bea

具体代码如下: 代码如下: //定义函数 function people(name,sex,age){ this.name = name; this.sex = sex; this.age = age; } //共享isStudent与sayName方法 people.prototype = { isStudent:true, sayName:function(){ alert(this.name); } } var people1
具体代码如下:


代码如下:


//定义函数
function people(name,sex,age){
 this.name = name;
 this.sex = sex;
 this.age = age;
}
 
//共享isStudent与sayName方法
people.prototype = { 
 isStudent:true,
 sayName:function(){
  alert(this.name);
 }
}
 
var people1 = new people('韩梅梅','女',16);  //实例化对象1
var people2 = new people('李磊','男',17);    //实例化对象2
 
//通过共享的方法让两个对象说出自己的名字
people1.sayName();
people2.sayName();
 
//通过共享的参数判断他们都是学生
if(people1.isStudent == people2.isStudent)alert('他们都是学生');


本文也提到了一些javascript对象的相关知识,应该不难理解。如果实在不明白的话可以稍微百度一下。



有用  |  无用

猜你喜欢