理解prototype

  • C.pototype用于建立由new.C创建的对象的原型;
  • Object.getPrototypeOf(obj)是ES5中用来获取obj对象的原型对象的标准方法。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
function User(name,passwordHash){

this.name = name;

this.passwordHash = passwordHash;

}

User.prototype.toString = function(){

return "[User"+this.name+"]";

};

User.prototype.checkPass = function(password){

}

var u = new User('ss','ssssss123456');

我们给USer函数添加两个方法到User.prototypr对象中,当我们使用new操作符创建User的实例时,产生的对象u得到了自动分配的原型对象。

u.name和u.passwordHash返回的是对象u的直接属性当前值,如果没有找到,才会去接着找u的原型对象,即User.prototype中的方法。

构造函数的prototype属性用来设置原型,那检测原型可以这样做:

Object.getPrototypeOf(u) === USer.prototype;//true

实例分析

那么怎么运用呢?

最近写了一个抽奖小游戏

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
function GiftsGame(jTarget, lotteryCode) {

this.wrapp = jTarget;

this.isWinner = false;

this.tipMsg = "";

this.responseCode = null;

this.isLogined = false;

this.code = lotteryCode;

this.lotteryPrize = [];

this.isGoing = 0;

this.hasChances = 1;

this.userLevel = 0;

this.isBegining = true;

this.theEnd = false;

var _this = this;

this.init();



_this.cookieValue = "";

} // GitGame函数保存一系列变量

以更新用户中奖名单的功能来说,通过建立原型方式调用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
GiftsGame.prototype.updateWinner = function() {

var _this = this;

setTimeout(function() {

});

}, 1);

/**

* 混淆用户pin

*/

function confusePin(pin) {

}

/**

* 滚动显示获奖信息

* @param wrapper

* @param time

*/

function autoScorll(wrapper, winnerLen) {

}

}

这种方法有什么好处呢,我是这么理解的,对于这个抽奖小游戏,大主体就是这个GiftsGame,实际上可以看成只有这个函数,下面都是这个函数的各个功能,这样的话就很有归纳和继承性,并且不会影响除这个游戏外的抽蛋小游戏和抓鸡小游戏的东西。