深刻理解JavaScript系列(10):JavaScript核心(晋级高手必读篇)

原型链html

 1 //prototype-chain  原型链--共用--继承
 2 var a = {
 3    x : 15,
 4    caculate : function(z){
 5        return this.x + this.y + z;
 6    }
 7 };
 8 
 9 var b = {
10     y : 5 ,
11     z : 20 ,
12     __proto__ : a
13};
14 
15 var c = {
16     y : 5 ,
17     z : 20 ,
18      __proto__ : a
19 };
20 
21 //调用继承过来的方法
22 a.caculate(22);    

说明:this这个值在一个继承机制中,仍然是指向它本来属于的对象,而不是从原型链上找到它时,它所属于的对象。例如,以上的例子,this.y是从b和c中获取的,而不是a。固然,你也发现了this.x是从a取的,由于是经过原型链机制找到的。函数

原型链一般将会在这样的状况下使用:对象拥有 相同或类似的状态结构(same or similar state structure) (即相同的属性集合)与 不一样的状态值(different state values)。在这种状况下,咱们可使用 构造函数(Constructor) 在 特定模式(specified pattern) 下建立对象。this

 1 // 构造函数
 2 function Foo(y) {
 3   // 构造函数将会以特定模式建立对象:被建立的对象都会有"y"属性
 4   this.y = y;
 5 }
 6  
 7 // "Foo.prototype"存放了新建对象的原型引用
 8 // 因此咱们能够将之用于定义继承和共享属性或方法
 9 // 因此,和上例同样,咱们有了以下代码:
10  
11 // 继承属性"x"
12 Foo.prototype.x = 10;
13  
14 // 继承方法"calculate"
15 Foo.prototype.calculate = function (z) {
16   return this.x + this.y + z;
17 };
18  
19 // 使用foo模式建立 "b" and "c"
20 var b = new Foo(20);
21 var c = new Foo(30);
22  
23 // 调用继承的方法
24 b.calculate(30); // 60
25 c.calculate(40); // 80
26  
27 // 让咱们看看是否使用了预期的属性
28  
29 console.log(
30  
31   b.__proto__ === Foo.prototype, // true
32   c.__proto__ === Foo.prototype, // true
33  
34   // "Foo.prototype"自动建立了一个特殊的属性"constructor"
35   // 指向a的构造函数自己
36   // 实例"b"和"c"能够经过受权找到它并用以检测本身的构造函数
37  
38   b.constructor === Foo, // true
39   c.constructor === Foo, // true
40   Foo.prototype.constructor === Foo // true
41  
42   b.calculate === b.__proto__.calculate, // true
43   b.__proto__.calculate === Foo.prototype.calculate // true
44  
45 );

文章源自Tom大叔博客JavaScript核心篇  http://www.cnblogs.com/TomXu/archive/2012/01/12/2308594.htmlspa

相关文章
相关标签/搜索