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

时间:2015-03-13    点击:74   

具体代码如下:

复制代码 代码如下:

//定义函数
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对象的相关知识,应该不难理解。如果实在不明白的话可以稍微百度一下。

JavaScript内存管理介绍
JavaScript中的this关键字使用方法总结
javascript中slice(),splice(),split(),substring(),substr()使用方法
在linux中使用包管理器安装node.js
JQuery中serialize() 序列化
> 返回     
地址:上海市普陀区胶州路941号长久商务中心 电话: QQ:
© Copyright 2012 上海网络 Product All Rights Reserved