js原型链的原理图

任何一个对象都有一个prototype的属性,在js中可以把它记为:__proto__
 

当初ECMAscript的发明者为了简化这门语言,同时又保持继承的属性,于是就设计了这个链表。。
在数据结构中学过链表不,链表中有一个位置相当于指针,指向下一个结构体。

于是乎__proto__也一样,每当你去定义一个prototype的时候,相当于把该实例的__proto__指向一个结构体,那么这个被指向结构体就称为该实例的原型。

文字说起来有点儿绕,看图说话

复制代码 代码如下:

var foo = {
x: 10,
y: 20
};

 

Figure 1. A basic object with a prototype.


当我不指定__proto__的时候,foo也会预留一个这样的属性,

如果有明确的指向,那么这个链表就链起来啦。

很明显,下图中b和c共享a的属性和方法,同时又有自己的私有属性。

__proto__默认的也有指向。它指向的是最高级的object.prototype,而object.prototype的__proto__为空。

复制代码 代码如下:

var a = {
x: 10,
calculate: function (z) {
return this.x + this.y + z
}
};
var b = {
y: 20,
__proto__: a
};

var c = {
y: 30,
__proto__: a
};

// call the inherited method
b.calculate(30); // 60

 

Figure 2. A prototype chain.


理解了__proto__这个属性链接指针的本质。。再来理解constructor。

当定义一个prototype的时候,会构造一个原形对象,这个原型对象存储于构造这个prototype的函数的原形方法之中.

复制代码 代码如下:
 
/ a constructor function
function Foo(y) {
  // which may create objects
  // by specified pattern: they have after
  // creation own "y" property
  this.y = y;
}
 
// also "Foo.prototype" stores reference
// to the prototype of newly created objects,
// so we may use it to define shared/inherited
// properties or methods, so the same as in
// previous example we have:
 
// inherited property "x"
Foo.prototype.x = 10;
 
// and inherited method "calculate"
Foo.prototype.calculate = function (z) {
  return this.x + this.y + z;
};
 
// now create our "b" and "c"
// objects using "pattern" Foo
var b = new Foo(20);
var c = new Foo(30);
 
// call the inherited method
b.calculate(30); // 60
c.calculate(40); // 80
 
// let's show that we reference
// properties we expect
 
console.log(
 
  b.__proto__ === Foo.prototype, // true
  c.__proto__ === Foo.prototype, // true
 
  // also "Foo.prototype" automatically creates
  // a special property "constructor", which is a
  // reference to the constructor function itself;
  // instances "b" and "c" may found it via
  // delegation and use to check their constructor
 
  b.constructor === Foo, // true
  c.constructor === Foo, // true
  Foo.prototype.constructor === Foo // true
 
  b.calculate === b.__proto__.calculate, // true
  b.__proto__.calculate === Foo.prototype.calculate // true
 
);
 

 

Figure 3. A constructor and objects relationship.

http://dmitrysoshnikov.com/ecmascript/javascript-the-core/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值