看了Tomxu 的文章,特写下一个他的一个js程序的执行过程。

移动互联 2012-09-14

看了
Tomxu
的文章,特写下一个他的一个js程序的执行过程。

function ConcreteClass(){

this.performTask=function(){

console.log(this)

this.preTask();

console.log('一些代码');

this.postTask();

}

}

ConcreteClass.prototype.add=function(){console.log('测试使用。')}

function AbstractDecorator(decorated){//抽象类 Abstract

this.performTask=function(){

decorated.performTask();

}

}

function ConcreteDecoratorClass(decorated){

this.base=AbstractDecorator;

this.base(decorated);

decorated.preTask=function(){

console.log('pre-calling...');

}

decorated.postTask=function(){

console.log('post-calling...');

}

}

var c1=new ConcreteClass();

var d1=new ConcreteDecoratorClass(c1);

d1.performTask();

var c2=new ConcreteClass();

//新添加,以上为Tom大叔的代码

c2.preTask();// TypeError: c2.preTask is not a function

var d2=new ConcreteDecoratorClass();

d2.performTask();//TypeError: decorated is undefined

上面程序执行过程如下:

1.载入后,分别注册3个函数ConcreteClass、AbstractDecorator、ConcreteDecoratorClass,但不执行内部方法

2.var c1=new ConcreteClass();执行至此时,跳到ConcreteClass函数内部,进行属性或方法的添加,添加performTask方法,但不执行

3.var d1=new ConcreteDecoratorClass(c1);执行至此时:

A:跳到ConcreteClass函数内部,添加base属性,this.base=AbstractDecorator;

this.base=function AbstractDecorator(decorated){//抽象类 Abstract

this.performTask=function(){

decorated.performTask();

}

}

接着顺序执行decorated.preTask、decorated.postTask 为c1对象实例添加了这2个方法

B:this.base(decorated);变为AbstractDecorator(c1),并立即执行,跳转至函数AbstractDecorator(decorated)中,

它里面的this代表ConcreteDecoratorClass【当前作用域】,添加属性performTask,且

this.performTask=function(){

c1.performTask();

}

即对象实例d1拥有了performTask属性而不是构造函数ConcreteDecoratorClass的属性

C:c2.preTask();执行至此时,在对象实例中开始查找preTask()方法并执行

查找过程:从ConcreteClass构造函数中查找,当走到this.base(decorated);时,查找到了:

this.performTask=function(){

c1.performTask();

}

故this.performTask()至c1.performTask();,故c2.preTask()变成c1.performTask(),至此执行c1内部的‘

this.preTask();

console.log('一些代码');

this.postTask();

以上执行完毕。

var c2=new ConcreteClass();

c2.preTask();// TypeError: c2.preTask is not a function

var d2=new ConcreteDecoratorClass();

d2.performTask();//TypeError: decorated is undefined

对于这2个是为了查看ConcreteClass中和ConcreteDecoratorClass

责编内容by:博客园-搜索引擎研究团队 (源链)。感谢您的支持!

您可能感兴趣的

Understanding Memoization In 3 Minutes There are several excellent articles that talk about the optimization technique...
Optimising web page: a simple step Single page applications (SPA) has become increasingly mainstream. Thanks to tho...
还在找什么,JavaScript的异步编程解决方案全在这里了... 阿里巴巴前端工程师逸翾对JavaScript中的异步编程进行了详细讲解。JavaScript的特点就是单线程,本文首先对单线程异步的原理进行了解读,接着着...
Fit Image(s) in a liquid Parent I am trying to present an Image Slider in a liquid layout (parent) and I do not ...
Until the animation is complete until you replace ... I am having trouble changing the contents of a div. What I want to achieve is...