---
title: "dojo生命周期管理"
author: "netliving"
date: "2012-11-20T14:32:15Z"
tags: []
categories: ["Web前端"]
slug: "dojo"
draft: false
lastmod: "2012-11-20T14:32:15Z"
id: 1730604
url: "https://netliving.iteye.com/blog/1730604"
---

今天简单看了一下dojo的declare源代码，发现了实例化化的代码，才真正理解了生命周期的原理，以前从网上只是看到了生命周期的几个方法，如果组织的一直没有发现，今天终于发现了。
declare他主要是dojo的继承机制，由于dojo支持多继承方式，所以dojo采用了C3算法，将多个继承关系转换为单继承链，然后满足继承要求。同时在继承的时候

```javascript

ctor.prototype = proto;
proto.constructor = ctor;

```

其中ctor为返回的对象，也就是说他会自动执行自身的constructor方法，完成对象的构建，构建完成在以后，执行对象本身，本身的代码如下定义

```javascript

bases[0] = ctor = (chains && chains.constructor === "manual") ? simpleConstructor(bases) :
			(bases.length == 1 ? singleConstructor(props.constructor, t) : chainedConstructor(bases, t));

```


其中多继承方式的构造如下定义

```javascript

	// chained constructor compatible with the legacy declare()
	function chainedConstructor(bases, ctorSpecial){
		return function(){
			var a = arguments, args = a, a0 = a[0], f, i, m,
				l = bases.length, preArgs;

			if(!(this instanceof a.callee)){
				// not called via new, so force it
				return applyNew(a);
			}

			//this._inherited = {};
			// perform the shaman's rituals of the original declare()
			// 1) call two types of the preamble
			if(ctorSpecial && (a0 && a0.preamble || this.preamble)){
				// full blown ritual
				preArgs = new Array(bases.length);
				// prepare parameters
				preArgs[0] = a;
				for(i = 0;;){
					// process the preamble of the 1st argument
					a0 = a[0];
					if(a0){
						f = a0.preamble;
						if(f){
							a = f.apply(this, a) || a;
						}
					}
					// process the preamble of this class
					f = bases[i].prototype;
					f = f.hasOwnProperty("preamble") && f.preamble;
					if(f){
						a = f.apply(this, a) || a;
					}
					// one peculiarity of the preamble:
					// it is called if it is not needed,
					// e.g., there is no constructor to call
					// let's watch for the last constructor
					// (see ticket #9795)
					if(++i == l){
						break;
					}
					preArgs[i] = a;
				}
			}
			// 2) call all non-trivial constructors using prepared arguments
			for(i = l - 1; i >= 0; --i){
				f = bases[i];
				m = f._meta;
				f = m ? m.ctor : f;
				if(f){
					f.apply(this, preArgs ? preArgs[i] : a);
				}
			}
			// 3) continue the original ritual: call the postscript
			f = this.postscript;
			if(f){
				f.apply(this, args);
			}
		};
	}


```

看到其中的注释1,2,3了吗，那就是他的实例化的过程，也就是可以扩展的定义步骤。