JavaScript面向对象编程(3)prototype简介

释放双眼,带上耳机,听听看~!

prototype——原型,用于给对象动态地新增属性和行为

先定义个构造函数


1
2
3
4
5
6
7
8
9
10
11
12
1//小配件
2function Gadget(name, color) {
3   this.name = name;
4   this.color = color;
5   this.whatAreYou = function(){
6       return '我是 ' + this.color + '的' + this.name;
7   }
8   this.get = function(what){
9       return this[what];//对象与数组有类似之处,js的[]中可以是下标,也可以是对象的属性
10  }
11}
12

1
2
1  使用prototype增加属性和方法  
2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
1/*使用prototype增加属性和方法*/
2Gadget.prototype.price = 100;//增加属性
3Gadget.prototype.rating = 3;
4//增加行为==方法==或者叫函数
5Gadget.prototype.getInfo = function() {
6   return '等级: ' + this.rating + ', 价格: ' + this.price;
7};
8
9/*也可批量替换或新增*/
10Gadget.prototype = {
11  price:100,
12  rating:3,
13  getInfo:function() {
14      //可访问原始属性
15<span style="white-space:pre">        </span>return '名字:'+this.name+',等级: ' + this.rating + ', 价格: ' + this.price;
16  }
17};
18
19var toy = new Gadget('网络摄像头','黑色');
20alert(toy.getInfo());//可访问新的方法,也可访问原有的属性和方法
21

/*属性的遍历及判断*/


1
2
3
4
5
6
7
8
1for(i in toy){
2
3
4   if(typeof(toy[i])!="function")
5       //遍历出toy上可以访问的所有的属性及属性值
6       alert(i + '=' + toy[i]);
7}
8

1
2
3
4
5
6
7
1//判断属性是不是原始的
2for(prop in toy){
3<span style="white-space:pre"> </span>if (toy.hasOwnProperty(prop)) {
4<span style="white-space:pre">     </span>alert("原始:"+prop + '=' + toy[prop]);
5<span style="white-space:pre"> </span>}
6}
7

每个对象都有isPrototypeOf方法,用于判断当前对象是不是另外一个对象的prototype


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
1/*Every object also gets the isPrototypeOf() method.
2 * This method tells you whether that specific object is used as a prototype of another object.
3每个对象都有isPrototypeOf方法,用于判断当前对象是不是另外一个对象的prototype
4* */
5var monkey = {
6   hair: true,
7   feeds: 'bananas',
8   breathes: 'air'
9};
10
11function Human(name) {
12  this.name = name;
13}
14
15Human.prototype = monkey;
16var george = new Human('George');
17
18alert("monkey.isPrototypeOf(george)==="+ monkey.isPrototypeOf(george));
19

1
2
1  总结:  
2

可以将prototype看做是一个额外的对象,在构造器上引用一个prototype对象,这个对象拥有一些属性和方法;

通过构造函数产生的对象也自然链接了这个prototype对象,而且可以把prototype对象的属性和方法当做自己的;

当然,原始的属性和通过prototype获得的属性还是有些不一样,至少通过hasOwnProperty可以判断出这个属性是不是自己的原生属性;

另外,可以通过a.isPrototypeOf(b)来判断a是不是b的prototype。

给TA打赏
共{{data.count}}人
人已打赏
安全技术

常用加密解密算法【RSA、AES、DES、MD5】介绍和使用

2021-8-18 16:36:11

安全技术

C++ 高性能服务器网络框架设计细节

2022-1-11 12:36:11

个人中心
购物车
优惠劵
今日签到
有新私信 私信列表
搜索