Category Archives: Lifestream

Node.js Best Practices | Just Build Something

I’ve recently been working on a lot of Node.js projects, for myself, with my students, and for national organizations. Because I’m a University instructor I’ve been getting a lot of questions about what the best practices for Node.js are from every project I’m involved with. I’ve worked with Node.js for years and know all the best practices myself, but I had never seen a list that explained the best practices to my satisfaction. So, I have put one together taking all the best practices agreed on by the community and explaining why each practice is the best way to write Node.js code.

If you want to improve these best practices in any way please don’t hesitate to create a pull request to the GitHub repo.

Here we go.

Before you comment with TL;DR notice that below are links to a description of each best practice. You can skip around and read the ones you are most interested in. The descriptions are concise and worth reading.

  1. Always Use Asynchronous Methods
  2. Never require Modules Inside of Functions
  3. Save a reference to this Because it Changes Based on Context
  4. Always “use strict”
  5. Validate that Callbacks are Callable
  6. Callbacks Always Pass Error Parameter First
  7. Always Check for “error” in Callbacks
  8. Use Exception Handling When Errors Can Be Thorwn
  9. Use module.exports not just exports
  10. Use JSDoc
  11. Use a Process Manager like upstart, forever, or pm2
  12. Follow CommonJS Standard

Always Use Asynchronous Methods

The two most powerful aspect of Node.js are it’s non-blocking IO and asynchronous runtime. Both of these aspects of Node.js are what give it the speed and robustness to serve more requests faster than other languages.

In order to take advantage of these features you have to always use asynchronous methods in your code. Below is an example showing the good and bad way to read files from a system.

The Bad Way reads a file from disk synchronously.

var data = fs.readFileSync('/path/to/file');
console.log(data);
// use the data from the file

The Good Way reads a file from disk asynchronously.

fs.readFile('/path/to/file', function (err, data) {
	// err will be an error object if an error occured
	// data will be the file that was read
	console.log(data);
});

When a synchronous function is invoked the entire runtime halts. For example, above The Bad Way halts the execution of any other code that could be running while the file is read into memory. This means no users get served during this time. If your file takes five minutes to read into memory no users get served for five minutes.

By contrast The Good Way reads the file into memory without halting the runtime by using an asynchronous method. This means that if your file takes five minutes to read into memory all your users continue to get served.

Never require Modules Inside of Functions

As stated above you should always use asynchronous methods and function calls in Node. The one exception is the require function, which imports external modules.

Node.js always runs require synchronously. This is so the module being required can require other needed modules. The Node.js developers realize that importing modules is an expensive process and so they intend for it to happen only once, when you start your Node.js application. They even cache the required modules so they won’t be requried again.

However, if you require an external module from within functions your module will be synchronously loaded when those functions run and this can cause two problems.

To explain one of the problems imagine you had a module that took 30 minuets to load, which is unreasonable, but just imagine. If that module is only needed in one route handler function it might take some time before someone triggers that route and Node.js has to require that module. When this happens the server would effectively be inaccessible for 30 minutes as that module is loaded. If this happens at peak hours several users would be unable to get any access to your server and requests will queue up.

The second problem is a bigger problem but builds on the first. If the module you require causes an error and crashes the server you may not know about the error for several days, especssially is you use this module in a rarely used route handler. No one wants a call from a client at 4AM telling them the server is down.

The solution to both of these problems is to always require modules at the top of your file, outside of any function call. Save the required module to a variable and use the variable instead of re-requiring the module. Node.js will save the module to that variable and your code will run much faster.

var _ = require('underscore');

function myFunction(someArray){

	// use underscore without the need
	// to require it again
	_.sort(someArray, function(item){
		// do something with item
	});

}

module.exports.myFunction = myFunction;

Save a reference to this Because it Changes Based on Context

If you have a background with Java, ActionScript, PHP, or basically any language that uses the this keyword you might think you understand how JavaScript treats the same keyword. Unfortunately you would be wrong.

Let me tell you how this is determined officially by ECMAScript.

The this keyword evaluates to the value of the ThisBinding of the current execution context.

Basically that means that the value of the this variable is determined based on context, not encapsulation, as it is in other languages.

For example, if this is used inside a function, this references the object that invoked the function. That means that if you create a constructor function (basically a class in JavaScript) which then has methods attached to it, the this variable in those methods may not refer to the constructor function (class) they are inside of.

The above happens a lot in Node, but it might be hard to understand without seeing code.

In the code below this has two different values.

function MyClass() {
	this.myMethod = function() {
		console.log(this);
	};
}

var myClass = new MyClass();
myClass.myMethod(); // this resolves as the instance of MyClass

var someFunction = myClass.myMethod;
someFunction(); // this resolves as the window in a browser and the global object in Node

The best way to solve this is to preserve this as another variable and then use that other variable instead. The most common variable names to use are _this, that, self, or root.

I personally like _this or self best because _this is easy to understand and self will be understood by anyone with Python or Ruby experience as both languages use self instead of this.

After making the changes your code should look like this.

function MyClass() {
	var self = this;
	this.myMethod = function() {
		console.log(self);
	};
}

var myClass = new MyClass();
myClass.myMethod(); // self resolves as the instance of MyClass

var someFunction = myClass.myMethod;
someFunction(); // self also resolves as the instance of MyClass

self now always refers to the MyClass instance.

Always “use strict”

“use strict” is a behavior flag you can add to to first line of any JavaScript file or function. It causes errors when certain bad practices are use in your code, and disallows the use of certain functions, such as with.

Believe it or not but the best place I found to describe what JavaScript’s strict mode changes is Microsoft’s JavaScript documentation.

Validate that Callbacks are Callable

As stated before Node.js uses a lot of callbacks. Node.js is also weakly typed. The compiler allows any variable to be converted to any other data type. This lack of typing can cause one big problem.

Only functions are callable.

This means that if you pass a string to a function that needed a callback function your application will crash when it tries to execute that string.

This is obviously bad, but upon first blush there is no simple way to solve it. You could wrap the execution of all callbacks in try catch statements, or you could use if statements to determine if a callback has been passed in.

However, there is a simple way of validating that callbacks are callable which requires only one line of code, and it accounts for optional callbacks as well as checking data type.

callback = (typeof callback === 'function') ? callback : function() {};

This determines if the callback is a function. If it’s not a function for any reason it creates an empty function and sets the callback to be that function. This way all callbacks are callable and optional.

Place that line at the top of each function that receives a callback and you will never crash due to uncallable callbacks again.

Callbacks Always Pass Error Parameter First

Node.js is asynchronous, which means you usually have to use callback functions to determine when your code completes.

After writing Node.js code for a while you will want to start writing your own modules, which need callback functions to be passed in by the user of your module. If an error occurs in your module, how do you communicate that to the user of the module? If you’re a Java developer you might think you should throw an exception, but throwing an exception in Node.js could potentially shutdown the server. Instead you should package the error into an object, and pass it to the callback function as the first parameter. If no error occurred you should pass null.

By convention all callback functions are passed an error as the first parameter.


function myFunction(someArray, callback){

	// an example of an error that could occur
	// if the passed in object is
	// not the right data type
	if( !Array.isArray(someArray) ){
		var err = new TypeError('someArray must be an array');
		callback(err, null);
		return;
	}

	// ... do other stuff

	callback(null, someData);

}

module.export.myFunction = myFunction;

Always Check for “error” in Callbacks

As stated above, by convention an error is always the first parameter passed to any callback function. This is great for making sure your site doesn’t crash and that you can detect errors when they happen.

Now that you know what they are you should start using them. If your database query errors out you need to check for that before using the results. I’ll give you an example.

myAsyncFunction({
		some: 'data'
	}, function(err, someReturnedData) {

		if(err){
			// don't use someReturnedData
			// it's not populated
			return;
		}

		// do something with someReturnedData
		// we know there was no error

	}
});

Use Exception Handling When Errors Can Be Thrown

Most methods in Node.js will follow the “error first” convention, but some functions don’t. These functions are not Node.js specific function, they instead come from JavaScript. There are lots of functions that can cause exceptions. One of these functions is JSON.parse which throws an error if it can’t parse a string into JSON.

How do we detect this error without crashing our server?

This is a perfect time to use a classic JavaScript try catch.


var parsedJSON;

try {
	parsedJSON = JSON.parse('some invalid JSON');
} catch (err) {
	// do something with your error
}

if (parsedJSON) {
	// use parsedJSON
}

You can now be sure that the JSON was parsed correctly before using it.

This can be even more useful when using it in modules.

function parseJSON(stringToParse, callback) {

	callback = (typeof callback === 'function') ? callback : function() {};

	try {

		var parsedJSON = JSON.parse(stringToParse);

		callback(null, parsedJSON);

	} catch (err) {

		callback(err, null);

		return;

	}


}

Of course the above example is slightly contrived, however, the idea of using try catch is a very good practice.

Use module.exports not exports

You might have used module.exports and exports interchangeably thinking they are the same thing and in may cases they are. However, exports is more of a helper method that collects properties and attaches them to module.exports.

So what the problem? That sounds great.

Well don’t get too excited. exports only collects properties and attaches them if module.exports doesn’t already have existing properties. If module.exports has any properties, everything attached to exports is ignored and not attached to module.exports.

module.exports = {};

exports.someProperty = 'someValue';

someProperty won’t be exported as part of the module.

var exportedObject = require('./mod');

console.log(exportedObject); // {}

The solution is simple. Don’t use exports because it can create confusing, hard to track down bugs.

module.exports = {};

module.exports.someProperty = 'someValue';

someProperty will be exported as part of the module.

var exportedObject = require('./mod');

console.log(exportedObject); // { someProperty: 'someValue' }

Use JSDoc

JavaScript is a weakly typed language. Any variable can be passed to any function without conflict, until you try to use that function.

function multiply(num1, num2) {

	return num1 * num2;

}

var value = multiply('Some String', 2);

console.log(value) // NaN

Obviously this is a problem above that could easily be fixed by looking at the code. But what if the code was written by someone else and uses complex parameters that you don’t really understand. You could spend several minutes tracking down the expected data type. Worst yet it might accept multiple data types, in which case it may take you longer to track it down.

The best thing to do is use JSDoc. If you’re a Java developer you will have heard of Javadoc. JSDoc is similar and at it’s simplest adds comments above functions to describe how the function works, but it can do a lot more.

Some IDEs will even use JSDoc to make code suggestions.

Use a Process Manager like upstart or forever

Keeping a Node.js progress running can be daunting. Simply using the node command is dangerous. If your Node.js server crashes the node command won’t automatically restart the process.

However, programs like upstart and forever will.

While upstart is a general purpose init daemon forever and pm2 are specific to Node.

Follow CommonJS Standard

Node.js follows a standard for writing code that varies slightly from the standards that govern writing browser based JavaScript.

This standard is called CommonJS.

While CommonJS is far too large for me to cover here it’s worth knowing about about and learning. The most important point are that it mandates certain file organization and behavior that should be expected from the CommonJS module loader (require). It also describes how internals of the Node.js system should work.

Check it out.

Conclusion

That was long but hopefully worth it. These are the main best practices of Node.js that everyone should be following.

Of course there are more best practices that can be followed, like only using one module.exports per module and one return per function, but these will only help with debugging.

Now that you know these best practices I hope either have validated your current way of working or your code improves and that you can write bigger better applications with less confusion.

If you have any questions please don’t hesitate to email me at alanjames1987@gmail.com. I do answer quickly and love talking about programming.

حدیث هایی در مورد مسلمان

 

 

1- حضرت محمد (صلی الله علیه و آله و سلّم) می فرمایند: کسی که در هر صبحگاه به امور مسلمین همّت نگمارد و در اندیشه ی کارهای آنان نباشد از آنها نیست وکسی که بشنود مردی فریاد می زند:«ای مسلمان ها بدادم برسید» و جواب او را ندهد مسلمان نیست. 

منبع : اصول کافی٬ ج٢/ص١۶۴٬ حدیث۵.

2- حضرت محمد (صلی الله علیه و آله و سلّم) می فرمایند: کسی که صبح کند و بفکر گره گشایی دیگر مسلمین نباشد، مسلمان حقیقی نیست.

منبع : اصول کافی

3- حضرت امام رضا (علیه السّلام) می فرمایند: مسلمان واقعی کسی است که مسلمانان از زبان و دست او در امان باشند.

منبع: مسند،ج1،ص260

4- حضرت موسی بن جعفر روایت کرده اند که رسول اکرم (صلی الله علیه و آله و سلّم) فرمودند: مسلمان نیست آنکس که به عهد و پیمان وفادار نباشد.

منبع : بحار جلد 16ص144

5- رسول اکرم (صلی الله علیه و آله و سلّم)فرموده اند: بر هیچ مسلمانی جایز نیست که خود را ذلیل و خوار نماید.

منبع : تاریخ یعقوبی ،ص67

6- رسول اکرم (صلی الله علیه و آله و سلّم) فرموده اند: خواستن رزق مباح و گذران کردن از درآمد حلال وظیفه ی واجب هر مرد و زن مسلمان است.

منبع : بحار 23،ص6

7- رسول اکرم (صلی الله علیه و آله و سلّم)می فرمودند : مسلمانی که از یک گناه اعراض کند اجر هفتاد حج مقبول در پیشگاه خداوند دارد.

منبع : مستدرک الوسائل جلد2 ص302

تناسب نعمت ها با استعدادهای گوناگون

8- حضرت امام علی (علیه السّلام) می فرمایند: پس از ستایش پروردگار، بدانید که تقدیرهای الهی چون قطرات باران از آسمان به سوی انسان ها فرود می آید، و بهره ی هر کسی، کم یا زیاد به او می رسد پس اگر یکی از شما برای برادر خود، برتری در مال و همسر و نیروی بدنی مشاهده کند، مبادا فریب خورد و حسادت کند؛ زیرا مسلمان (تا زمانی که دست به عمل پستی نزده که از آشکار شدنش شرمنده باشد و مورد سرزنش مردم پست قرار گیرد.) به مسابقه دهنده ای (1) می ماند که دوست دارد در همان آغاز مسابقه پیروز گردد تا سودی به دست آورد و ضرری متوجه او نگردد. هم چنین مسلمانی که از خیانت پاک است انتظار دارد یکی از دو خوبی نصیب او گردد: یا دعوت حق را لبیک گفته عمر او پایان پذیرد (( که آنچه در نزد خداست برای او بهتر است))؛ و یا خداوند روزی فراوان به او دهد و صاحب همسر و فرزند و ثروت گردد، و هم چنان دین و شخصیت خود را نگاه دارد. همانا ثروت و فرزندان، محصول دنیا و فانی شدنی و عمل صالح زراعت آخرت است، گر چه گاهی خداوند، هر دوی آن را به ملت هایی خواهد بخشید. از خدا در آنچه اعلام خطر کرده است بر حذر باشید! از خدا آن گونه بترسید که نیازی به عذر خواهی نداشته باشید! عمل نیک انجام دهید بدون آن که به ریا و خودنمایی مبتلا شوید؛ زیرا هرکس، کاری برای غیر خدا انجام دهد، خدا او را به همان غیر واگذارد. از خدا، درجات شهیدان، و زندگی سعادتمندان، و هم نشینی با پیامبران را درخواست می کنیم.

(1): فالج یاسر: در دوران جاهلیت شتری را می کشتند و برای تقسیم گوشت آن به مسابقه تیراندازی متوسّل می شدند؛ ده تیر بود که هفت عدد آن علامتی مخصوص داشت و سه تای آن بدون نشان بود هرکس که تیر او به هدف می خورد سهم بیشتری از گوشت شتر داشت. از این رو هر کسی دوست داشت که همان آغازین تیری را که رها می کند به هدف زده برنده مسابقه باشد.

منبع: نهج البلاغه،خطبه 23

9- حضرت امام حسین (علیه السّلام) فرمودند: کسی که برادر مسلمان خود را که بر او وارد شده است احترام نماید خدا را احترام کرده است.

منبع: وسادل،ج4،ص97

10- رسول اکرم (صلّی الله علیه و آله و سلّم) فرمودند: کسی که برادر مسلمان خود را با کلمات مودت آمیز خویش احترام نماید و غم او را بزداید، تا این سجیه در او باقی است پیوسته در سایه ی رحمت خداوند است.

منبع: بحار،ج16،ص84

11- رسول اکرم (صلّی الله علیه و آله و سلّم) فرمودند: هیچ یک از مسلمین را تحقیر نکنید و کوچک نشمارید زیرا مسلمانی که در نظر شما کوچک است نزد خداوند بزرگ است.

منبع: مجموعه ورام،ج1،ص31

13- رسول اکرم (صلّی الله علیه و آله و سلّم) فرموده اند: بر هیچ مسلمانی جایز نیست که خود را ذلیل و خوار نماید.

منبع : تاریخ یعقوبی ،ص67

14- حضرت امام صادق (علیه السّلام) فرموده اند: خداوند تمام کارهای هر مسلمانی را به خود او واگذار نموده اند مگر ذلیل کردن خود، یعنی مؤمن حق ندارد موجبات خواری و ذلّت خود را فراهم آورد.

منبع : کافی جلد 5 ص63

15- حضرت امام حسن عسکری (علیه السّلام) فرموده اند: چقدر قبیح است که در باطن مسلمان ، میل و رغبت به چیزی باشد که سبب ذلّت و خواری او شود.

منبع : تحف العقول ص489

16- حضرت امام صادق (علیه السّلام) فرموده اند: مردی به خانه ی رسول اکرم آمد و درخواست ملاقات داشت. موقعیکه حضرت خواستند از حجره خارج شوند و به ملاقات آن مرد بروند به جای آیینه ، جلوی ظرف بزرگ آبی که در داخل اطاق بود ایستاند و سر و صورت خود را مرتّب کرند، عایشه از مشاهده ی اینکار به عجب آمد، در مراجعت عرض کرد یا رسول الله چرا در موقع رفتن در برابر ظرف ایستادید و موی و روی خود را منظّم کردید، فرموند: عایشه، خداوند دوست دارد که وقتی مسلمانی برای دیدار برادرش می رود خود را بسازد و خویشتن را برای ملاقات او بیاراید.

منبع : مکارم الاخلاق ،ص51

17- رسول اکرم (صلی الله علیه و آله و سلّم) فرموده اند: هیچ یک از مسلمانان را کوچک و ناچیز نشمارید که خردسالان مسلمین هم در پیشگاه الهی بزرگند.

منبع : مجموعه ی ورّام جلد1 ص 31

18- با هم و کمک کردن به هم در مهرورزی و همراهی با نیازمندان و در مهرورزی به همدیگر تا بوده باشید چنانچه خدا عزوجل فرموده است: (( مهربانند به خویشتن یا مهربانان در میان خودشان)) (فتح آیه 29) با همدیگر مهربان باشید و غمناک شوید برای آنچه از کار مسلمانان در دسترس ندارید، بر همان روشی که انصار در دوران رسول خدا (صلّی الله علیه و آله و سلّم) داشتند.

منبع : اصول کافی جلد 4، ص 519

19- معلی بن خنیس، گوید: به حضرت امام صادق (علیه السّلام) گفتم: حق مسلمان بر مسلمان چیست؟ فرمود: برای او هفت حق واجب است که هر کدام در مقام خود واجب است بر او، اگر یکی از آنها را ضایع و بی اجرا گذارد از ولایت و اطاعت خدا بیرون است و برای خداوند هیچ بهره ای از بندگی در او نیست، به او گفتم: قربانت، آنها چیستند؟ فرمودند: ای معلی، به راستی که من بر تو مهربانم، و می ترسم که آنها را ضایع کنی و نگهداری نکنی و بدانی و بکار نبندی، گوید: به او گفتم: لاحول ولا قوة الا بالله، فرمودند: آسان تر آنها این حق است که : 1- دوست داری برای او آنچه را برای خود دوست داری و بد داری برای او آنچه را برای خود بد داری. 2- از خشم او کناره کنی و خشنودی او را پیروی کنی و فرمان او را ببری. 3- او را کمک کنی با خودت و داراییت و زبانت و دست و پایت. 4- چشم او و رهنمای او و آینه ی او باشی. 5- سیر نباشی و او گرسنه باشد، سیراب نباشی و او تشنه بماند، نپوشی و او لخت بگردد. 6- اگر تو را خدمتکاری است و برادرت را خدمتکاری نیست، خدمتکار خود را بفرستی تا جامه ی او را بشوید و خوراک او را بسازد و بستر او را پهن کند. 7- به سوگند او وفاداری کنی، دعوت او را بپذیری، بیمار شد به دیدارش روی و در جنازه ی او حاضر شوی و هرگاه بدانی او را حاجتی است به انجام آن برایش پیش دستی کنی و او را نداری تا از تو خواهش آن کند ولی بشتاب و در انجام آن بکوش و هرگاه چنین کردی دوستی خود را به دوستی او پیوستی و دوستی او را به دوستی خداوند پیوستی( این است معنی روابط دوستانه ی متبادله)

منبع : اصول کافی جلد 4، ص 501

20- عبدالاعلی بن اعین گوید: (برخی) از اصحاب ما نوشتند و چیزهایی از حضرت امام صادق (علیه السّلام) پرسیدند و به من فرمان دادند که از آن حضرت حق مسلمان را بر برادرش بپرسم، پرسیدم و به من پاسخی نداد، چون آمدم که با او وداع کنم، به ایشان گفتم: پرسیدم و جواب ندادید؟ فرمودند: من می ترسم شما کافر شوید، به راستی از سخت ترین چیزها که خدا بر خلقش واجب کرده سه تا است: 1- عدالت ورزی مرد از طرف خودش تا اینکه نپسندد برای برادرش از طرف خودش جز آنچه بپسندد برای خودش از طرف او.2- همراهی برادر با مال و دارایی.3- ذکر خدا در هر حال که نه لفظ سبحان الله والحمد لله است ولی در نزد آنچه خدا حرام کرده یاد خدا کند و آن را وانهد.

منبع : اصول کافی جلد 4، ص 503

21- ابراهیم بن عمر یمانی گوید حضرت امام صادق (علیه السّلام) فرمودند: حق مسلمان بر مسلمان این است که خود سیر نباشد و برادرش گرسنه باشد، و خود سیراب نباشد و برادرش تشنه باشد، و خود پوشیده نباشد و برادرش لخت باشد، وه چه بزرگ است حق مسلمان بر برادر مسلمان خودش و فرمودند: دوست بدار برای برادر مسلمانت آنچه را برای خود دوست می داری و هرگاه نیازمند شدی از او بخواه و اگراز تو خواستار شد به او بده، از هیچ کار خوبی درباره ی او دلتنگ و خسته مشو، و از هیچ کار خوبی برای تو دل تنگ و خسته نشود (هیچ خیری را از او فرو مگذار و پس مینداز و خیری را برایت فرو نگذارد و پس نیندازد) پشت او باش که او پشت تو است، چون غایب شود در پشت سر او نگهداری کن، و چون حاضر باشد از او دیدن کن، او را گرامی دار و ارجمند شمار زیرا او از تو است و تو از اویی و چون از تو گله ای دارد از او جدا مشو تا گذشت او را خواستار شوی، و اگر او به خیری رسد خدا را سپاس گزار و اگر گرفتار شود، زیر بازویش را بگیر و اگر برای او دامی نهادند و سخن چینی کردند، به او کمک کن و اگر مردی به برادرش بگوید اف بر تو، دوستی معنوی میان آنها بریده شود و وقتی به او بگوید: تو دشمن منی، یکی از آنها کافر باشد و اگر او را متهم سازد و به اوافترا بندد، ایمان در دلش آب شود چنانچه نمک در آب، و گفت: به من رسیده است که فرمود: به راستی مومن است که نورش برای اهل آسمانها می درخشد چنانچه ستاره های آسمان برای اهل زمین می درخشد و فرمود: به راستی مومن دوست خدا است که خدایش کمک کند و برای او بسازد و مومن برای خدا جز حق و درست نگوید و از جز او نترسد.

منبع : اصول کافی جلد 4، ص 505

22- حضرت امام صادق (علیه السّلام) فرمودند: حق مسلمان به برادر مسلمانش این است که: هرگاه به او برخورد سلامش کند، و هر وقت بیمار شد او را عیادت کند، و وقتی غایب شد برای او خیرخواهی کند، و چون عطسه زد به او دعای وارد را (یرحمک الله) بگوید، و چون از او دعوت کرد او را اجابت کند، و وقتی مرد از او تشییع کند.

منبع : اصول کافی جلد 4، ص 507

23- أبی المغرا گوید، حضرت امام صادق (علیه السّلام) فرمودند: مسلمان برادر مسلمان است، به او ستم نکند و او را واننهد و به او خیانت نورزد و بر مسلمانان سزا است که بکوشند در هم پیوستگی و کمک بر یکدیگر در مهرورزی و همراهی با نیازمندان و مهرورزی بر همدیگر تا بوده باشید چنانچه خدای عزوجل فرموده است: ((مهربانند به یکدیگر)) (سوره فتح آیه 29) در خوشی های هم شریک شوید و مهرورز باشید و غم خوار باشید نسبت به آنچه کار آنان در دسترس شما نیست، بر همان روشی که گروه انصار در دوران رسول خدا  (صلّی الله علیه و آله و سلّم) داشتند.

منبع : اصول کافی جلد 4، ص 517

24- رسول خدا  (صلّی الله علیه و آله و سلّم) فرمودند: مسلمان باید چون سفری خواهد، برادران خود را آگاه سازد و بر برادران او است که چون برگردد به دیدن او آیند.

منبع : اصول کافی جلد 4، ص 517

25- رسول خدا (صلّی الله علیه و آله و سلّم) فرمودند: جبرئیل برای ما بازگفت که خدا عزوجل فرشته ای را به زمین فرستاد و آن فرشته آمد و آغاز رفتن نمود تا گذرش بر دری افتاد که مردی بر آن ایستاده و از صاحب خانه اجازه ی ورود می خواست، آن فرشته به وی گفت: چه نیازی به صاحب این خانه داری در پاسخ گفت: برادر دینی من است و در راه خدا تبارک و تعالی از او دیدن کنم، آن فرشته به وی گفت: تو تنها برای همین آمدی؟ در پاسخ گفت: جز برای این کار نیامدم، به او گفت: من پیک خدایم به سوی تو و او به تو سلام می رساند و می فرماید: بهشت برای تو واجب است، آن فرشته گفت: خدا عزوجل می فرماید: هر مسلمانی از مسلمانی دیدن کند، او را دیدن نکرده پس مرا دیدن کرده و ثواب او بر من بهشت است.

منبع : اصول کافی جلد 4، ص 523

26- حضرت امام باقر (علیه السّلام) فرمودند: به راستی که چون بنده ی مسلمانی از خانه اش بیرون آید و از برادرش برای خدا نه برای چیز دیگری دیدن کند و رضای خدا جوید، شوق آنچه را داشته باشد که نزد خدا است، خدا عزوجل به او هفتاد هزار فرشته بگمارد که از دنبالش او را جار کشند تا برگردد به خانه اش که خوش باشی و خوش باشد برایت بهشت.

منبع : اصول کافی جلد 4، ص 527

27- ابی الجارود گوید: شنیدم حضرت امام باقر (علیه السّلام) می فرمودند: به راستی دوست داشتنی ترین کارها به درگاه خدا عزوجل شاد کردن مومن است یا سیر کردن مسلمانی یا پرداختن بدهکاری او.

منبع: اصول کافی جلد 4،ص 563

28- حضرت امام صادق (علیه السّلام) فرموده اند: هر که مسلمانی را شاد کند، خدا عزوجل او را شاد کند.

منبع: اصول کافی جلد 4،ص 573

29- ابی عبیده حذاء گوید، حضرت امام صادق (علیه السّلام) فرموده اند: هرکه در انجام حاجت برادر مسلمانش راه رود، خدا به وسیله ی هفتاد و پنج هزار فرشته بر او سایه افکند و گامی بر ندارد جز اینکه خدا برایش حسنه ای نویسد و گناهی بدان از وی بریزد و درجه ای بدان برایش بالا برد و چون از حاجت او فارغ شود، خدا عزوجل برای او مزد کسی که حج و عمره کرده بنویسد.

منبع: اصول کافی جلد 4، ص 585

30- حضرت امام صادق (علیه السّلام) فرموده اند: اگر من در انجام حاجت برادر مسلمانم راه بروم دوست داشتنی تر است برایم از اینکه هزار بنده آزاد کنم و در راه خدا هزار اسب با زین و لگام زیر پای مجاهدان بنهم.

منبع: اصول کافی جلد 4، ص 587

31- حضرت امام صادق (علیه السّلام) فرموده اند: هر که در انجام حاجت برادر مسلمانش بکوشد و رضای خدا جوید، خدا عزوجل برای او هزار حسنه بنویسد که در ضمن آن خویشان و همسایگان و برادران و آشنایان و هرکه در دنیا به او خوبی کرده آمرزیده شوند و چون روز رستاخیز شود به او گفته شود که به دوزخ برو و هرکه را دیدی که در دنیا به تو خوبی کرده به اجازه ی خدا عزوجل او را بیرون آور جز اینکه ناصبی و دشمن اهل بیت باشد.

منبع: اصول کافی جلد 4، ص 589

32- حضرت امام صادق (علیه السّلام) فرموده اند: هر که مومن را اطعام کند تا سیرش سازد، هیچ کس اندازه ی مزدی که در آخرت دارد نداند، نه فرشته ی مقرب و نه پیغمبر مرسل جز خدا پروردگار جهانیان، سپس فرمودند: از موجبات آمرزش ، اطعام مسلمان گرسنه است سپس قول خدا عزوجل را خواند: (( یا اطعام به روز قحطی(14) به یتیمی خویشاوند(15)، یا مستمندی خاک نشین(16).)(بلد،آیه ی 14 تا 16)

منبع: اصول کافی جلد 4، ص 599

33- عبدالله وصّافی گوید، امام باقر(علیه السّلام) فرمودند: اگر من یک مرد مسلمان را اطعام کنم، بهتر است برایم از اینکه یک افق از مردم را اطعام کنم، من گفتم: افق چه اندازه است؟ فرمودند: ده هزار.

منبع: اصول کافی جلد 4، ص601

34- سدیر صیرفی، گوید، حضرت امام صادق (علیه السّلام) به من فرمودند: چرا هر روز یک بنده آزاد نکنی؟ گفتم: دارایی من بدان نرسد، فرمودند: هر روز یک مسلمانی را اطعام کن، گفتم: دارا باشد یا ندار؟ گوید، فرمودند: دارا هم بسا باشد که طعامی خواهد.

منبع: اصول کافی جلد 4، ص 603

35- حضرت امام صادق (علیه السّلام) فرمودند: یک خوراکی که برادر مسلمانم نزد من بخورد، دوست داشتنی تر است نزد من از آزاد کردن یک بنده.

منبع: اصول کافی جلد 4، ص603

36- حضرت امام صادق (علیه السّلام) فرمودند: اگر پنج درهم برگیرم و در این بازار شما درآیم و خوراکی بخرم و چندتن از مسلمانان را گردش فراهم کنم، بهتر است نزد من از اینکه یک بنده آزاد کنم.

منبع: اصول کافی جلد 4، ص605

37- از امام باقر (علیه السّلام) پرسیده شد، با آزاد کردن بنده چه چیز برابر است؟ فرمودند: طعام یک مرد مسلمان.

منبع: اصول کافی جلد 4، ص605

38- حضرت امام صادق (علیه السّلام) فرموده اند: هرکه به یکی از فقرا مسلمانان که لخت است جامه ای بپوشاند یا چیزی برای معیشت و قوت او به وی کمک دهد، خدا عزوجل به او هفتاد هزار فرشته بگمارد تا برای هر گناهی که کرده تا صور بدمد آمرزش خواهد.

منبع: اصول کافی، ج4، ص609

39- حضرت امام صادق (علیه السّلام) فرموده اند: هرکه مقدم برادر مسلمان خود را که به او وارد شود گرامی دارد و از او احترام کند، همانا خدا عزوجل را گرامی داشته.

منبع: اصول کافی جلد 4، ص613

40- پیامبر اسلام (صلّی الله علیه و آله و سلّم) فرموده اند: هرکه برادر مسلمان خود را با سخنی، مهرورزی کند و گرامی دارد و گره گرفتاری او را بگشاید، پیوسته در سایه ی خدا است و با رحمت او مدد شود تا در این کار باشد.

منبع: اصول کافی جلد 4، ص613

41- حضرت موسی بن جعفر (علیه السّلام) روایت کرده است که رسول اکرم (صلی الله علیه و آله و سلّم) فرمودند: مسلمان نیست آن کس که به عهد و پیمان وفادار نباشد.

منبع : بحار جلد 16 ص144

42- رسول اکرم (صلّی الله علیه و آله و سلّم) فرموده اند: هیچ یک از مسلمانان را کوچک و ناچیز نشمارید که خردسالان مسلمین هم در پیشگاه الهی بزرگند.

منبع: مجموعه ی ورام، ج1، ص 31

43- حضرت امام صادق (علیه السّلام) فرموده اند: من در شگفتم از مرد مسلمان، خدا عزوجل چیزی برای او مقدر نکند جز این که خیر او است و اگر با مقراض او را ببرند و تیکه تیکه کنند خیر او است و اگر مشارق و مغارب را هم مالک شود، خیر او است.

منبع : اصول کافی جلد 4، ص 197

44- رسول اکرم (صلّی الله علیه و آله و سلّم) فرموده اند: مسلمانی که درختی غرس یا زراعتی سبز نماید مردم و طیور و پرندگان از آن بخورند اجر صدقه دارد.

منبع: مستدرک،ج2،ص501

45- حضرت امام علی (علیه السّلام) فرموده اند: مسلمانی که از یک گناه اعراض کند اجر هفتاد حج مقبول در پیشگاه خداوند دارد.

منبع: مستدرک الوسائل، ج2،ص302

 

www.ez12.persianblog.ir

با تشکر از انتخاب شما

Asynchronous method queue chaining in JavaScript

Thursday May 6 2010

Chaining. It's an extremely popular pattern these days in JavaScript. It's easily achieved by continually returning a reference to the same object between linked methods. However one technique you don't often see is queueing up a chain of methods, asynchronously, by which functions can be linked together independent of a callback. This discussion, of course, came from a late work night building the @anywhere JavaScript API with two other mad scientists, Russ D'Sa (@dsa) and Dan Webb (@danwrong). Anyway, let's have a look at some historical conventions and compare them to newer ones. Imagine an iterator class that operated on arrays. It could look like this:
// no chaining

var o = new Iter(['a', 'b', 'c', 'd', 'e']);

o.filter(function(letter) {

  if (letter != 'c') { return letter; }

});

o.each(function(letter) {

  append(letter);

});



// with chaining

new Iter(alphabet).filter(remove_letter_c).each(append);
This is a simple because we're working on a known existing object in memory (the alphabet array). However an easy way to spoil our soup is to make our methods continue to operate without existing objects. Like say, for example, a result set you had to make an async request to the server to get. Thus, imagine making this work:
ajax('/server/results.json').filter(remove_duplicates).append('div#results');
In the grand scheme of things, the above example isn't too far off from from currying (which it's not). And to make another point, currying can often lead to bad coupling of code... which in its defense, is often the point as well. Some libraries even call this pattern binding... so... yeah. Anyway, to the point, here is a basic Queue implementation that can be used as a tool to build your own asynchronous method chains.
function Queue() {

  // store your callbacks

  this._methods = [];

  // keep a reference to your response

  this._response = null;

  // all queues start off unflushed

  this._flushed = false;

}



Queue.prototype = {

  // adds callbacks to your queue

  add: function(fn) {

    // if the queue had been flushed, return immediately

    if (this._flushed) {

      fn(this._response);



    // otherwise push it on the queue

    } else {

      this._methods.push(fn);

    }

  },



  flush: function(resp) {

    // note: flush only ever happens once

    if (this._flushed) {

      return;

    }

    // store your response for subsequent calls after flush()

    this._response = resp;

    // mark that it's been flushed

    this._flushed = true;

    // shift 'em out and call 'em back

    while (this._methods[0]) {

      this._methods.shift()(resp);

    }

  }

};
With this code, you can put it straight to work for something useful, like say, a jQuery plugin that fetches content remotely and then appends the results to your selector input. For you plugin developers our there, it would look like this...

<script src="jquery.js"></script>

<script src="async-queue.js"></script>

<script>

(function($) {



  $.fn.fetch = function(url) {

    var queue = new Queue;

    this.each(function() {

      var el = this;

      queue.add(function(resp) {

        $(el).html(resp);

      });

    });



    $.ajax({

      url: url,

      dataType: 'html',

      success: function(html) {

        queue.flush(html);

      }

    });

    return this;

  };



})(jQuery);

</script>

Then voila! You can make your DOM queries, fetch remote content, and continue your chain, asynchronously.
$("<div/>")

  .fetch('/server/navigation.html')

  .addClass('column')

  .appendTo('#side');

Here's a brief example of showing off the example above. Point being, one can only imagine the possibilities you could do. Say for example, having multiple items in the queue waiting to operate on a response. Thus imagine this...
fetchTweet(url).linkify().filterBadWords().appendTo('#status');
Your internals would look like this with the Queue.

function fetchTweet(url) {

  this.queue = new Queue;

  this.tweet = "";

  var self = this;

  ajax(url, function(resp) {

    self.tweet = resp;

    self.queue.flush(this);

  });

}

fetchTweet.prototype = {



  linkify: function() {

    this.queue.add(function(self) {

      self.tweet = self.tweet.replace(/b@(w{1,20}b/g, '<a href="...">$1</a>');

    });

  return this;

  },



  filterBadWords: function() {

    this.queue.add(function(self) {

      self.tweet = self.tweet.replace(/b(fuck|shit|piss)b/g, "");

    });

  return this;

  },



  appendTo: function(selector) {

    this.queue.add(function(self) {

      $(self.tweet).appendTo(selector);

    });

  return this;

  }



};

And with that, you can call it a night. Cheers.

حدیث هایی در مورد پستی

 

 

1- حضرت امام صادق (علیه السّلام) می فرمودند: به شما سفارش می کنم پرهیزگار باشید و با ارتکاب گناه، مردم را بر خود مسلّط نکنید و خویشتن را دچار ذلّت و خواری ننمایید.

منبع : وسائل جلد 3 ص202

2- حضرت علی بن ابی طالب(علیه السّلام) به حضرت حسین (علیه السّلام)در ضمن وصایای خود فرموده اند: کسیکه نسبت به مردم تکبّر نماید ذلیل و خوار خواهد شد.

منبع : تحف العقول ، ص88

3- و نیز فرموده اند :چه بسا عزیزانی که اخلاق ناپسند ، آنها را به ذلّت و خواری انداخته و چه بسا مردم پست و کوچکی که صفات پسندیده ، آنان را عزیز و محبوب ساخته است.

منبع : سفینه ، خلق ص411

4- حضرت امام علی (علیه السّلام) فرموده اند: بنده شهوت، اسیری است که هرگز آزادی نخواهد داشت.

منبع : غرر الحکم ،ص499و765

5- حضرت امام علی (علیه السّلام) فرموده اند: کسیکه مغلوب شهوت خویشتن است ذلّت و خواریش بیش از برده ی زر خرید است.

منبع : غرر الحکم ،ص499و765

ذلت طمع و حرص

6- حضرت امام علی (علیه السّلام) فرموده اند: ذلت و پستی و بدبختی ، در خوی ناپسند حرص و آز نهفته است .

منبع : غررالحکم ، ص96

7- حضرت امام علی (علیه السّلام) فرموده اند: در نظر افراد آگاه و درّاک، خوی ناپسند حرص، مایه ی پستی و ذلّت است.

منبع : فهرست غرر ،ص61

8- حضرت امام علی (علیه السّلام) فرموده اند: آنکس که بیماری حرص بر جانش مستولی گردد، به خواری و ذلّت بزرگ دچار خواهد شد.

منبع : غررالحکم ،ص 629

9- حضرت امام علی (علیه السّلام) فرموده اند: حرص فراوان و طمع شدید یک انسان را می توان، دلیل بدی او گرفت و به آن استشهاد کرد.

منبع : فهرست غرر، ص63

10- حضرت امام علی (علیه السّلام) فرموده اند: کسیکه صفحه ی خاطر را از پستی طمع پاک نکند خویشتن را ذلیل و پست کرده و در قیامت به خواری و اهانت بیشتری گرفتار است.

منبع : غررالحکم ، ص690

11- حضرت امام علی (علیه السّلام) در عبارتی کوتاه و حکیمانه تنافی چند خواهش نفسانی را با یکدیگر بیان فرموده اند: چه عجیب و حیرت آور است کار بشر، اگر در موردی امیدوار شود طمع خوارش خواهد کرد ،اگر طمع او را به جنبش درآورد، حرص هلاکش می کند، اگر دچار ناامیدی شود غم و غصّه او را می کشد، اگر به خوشبختی و سعادت رسد نگاهداری آن را فراموش می کند، اگر دچار خوف و هراس شود از ترس حیرت زده می گردد ، اگر در گشایش امنیّت قرار گیرد غافل می شود، اگر نعمت بر او تجدید شود دچار گردن کشی و بلند پروازی می گردد ، اگر دچار مصیبتی شد تأثّر و حزن او را رسوا می کند، اگر ثروتی بدست آورد دچار طغیان مالی می گردد، اگر فقر گریبان گیرش شد غرق اندوه می شود، اگر گرفتار تعب گرسنگی شد از ناتوانی زمین گیر می گردد، و اگر در خوردن زیاده روی کند از فشار شکم ناراحت می شود، پس کندرویها در زندگی بشر مضر است و تندرویها نیز مایه ی ویرانی و فساد، هر خیری را شرّی و هر نوشی را نیشی است.

منبع : آداب النفس جلد 2 ص 111- ارشاد مفید ص142

12- حضرت امام علی (علیه السّلام) فرموده اند: حرص شدید به لذائذ و مشتهیات نفسانی ، آدمی را گمراه می کند و از راه سعادت و رستگاری منحرف می سازد و سرانجام باعث هلاکت و نابودی او می شود.

منبع : غررالحکم ،ص781

13- حضرت امام علی (علیه السّلام) فرموده اند: بردباری در فقر تؤام با عزّت ، بهتر از ثروت آمیخته به خواری و ذلّت است.

منبع : غررالحکم ،ص89

14- حضرت امام علی (علیه السّلام) فرموده اند: گرسنگی بهتر از ذلّت سرافکندگی و زبونی است.

منبع : فهرست غرر، ص125

15- حضرت امام علی (علیه السّلام) فرموده اند: گدائی طوق ذلّتی است که عزّت را از عزیزان و شرافت خانوادگی را از شریفان سلب می کند.

منبع : غررالحکم ،ص96

16- حضرت امام علی (علیه السّلام) فرموده اند: مردم از ترس خواری به سوی ذلت و خواری می شتابند و با این کار، پستی و حقارت خویش را افزایش می دهند.

منبع : غررالحکم ، ص104

17- رسول اکرم (صلّی الله علیه و آله و سلّم) فرموده اند: بر هیچ مسلمانی جایز نیست که خود را ذلیل و خوار نماید.

منبع : تاریخ یعقوبی ،ص67

18- حضرت امام صادق (علیه السّلام) می فرمودند: آدمی از ذلت و حقارت کوچکی اظهار ناراحتی و اندوه می کند و همین جزع و بی قراری ، او را به ذلت بزرگتری گرفتار می نماید.

منبع : تحف العقول ص366

19- حضرت امام علی (علیه السّلام) فرموده اند: یک ساعت ذلّت با عزّت تمام دوران زندگی برابری نمی کند.

منبع : غررالحکم ، ص434

20- حضرت امام سجاد (علیه السّلام) فرموده اند: دوست ندارم که با ذلت نفس به ارزنده ترین سرمایه ها و ثروتها دست یابم.

منبع : مستدرک 2، ص364

21- حضرت امام صادق (علیه السّلام) فرموده اند: خداوند تمام کارهای هر مسلمانی را به خود او واگذار نموده اند مگر ذلیل کردن خود، یعنی مؤمن حق ندارد موجبات خواری و ذلّت خود را فراهم آورد.

منبع : کافی جلد 5 ص63

22- حضرت امام حسن عسکری (علیه السّلام) فرموده اند: چقدر قبیح است که در باطن مسلمان ، میل و رغبت به چیزی باشد که سبب ذلّت و خواری او شود.

منبع : تحف العقول ص489

24- حضرت امام علی (علیه السّلام) فرموده اند: مرگ ، بر زندگی آمیخته به پستی و خواری ترجیح دارد.

منبع : نهج البلاغه ، کلمه ی 390

25- حضرت امام محمدباقر (علیه السّلام) فرموده اند: بد آدمی است آنکس که در خویشتن مِیلی را بپرورد که در راه رسیدن به آن دچار ذلت و خواری شود.

منبع : محجة البیضاء جلد 4 ص108

گفتار و رفتار ذلت آمیز

26- حضرت امام علی (علیه السّلام) فرموده اند: روزی رسول اکرم بر جمعی از اصحاب خود وارد شد . آنان با گشاده روئی و حسن احترام، حضرت را سید ومولای خود خواندند. پیغمبر اکرم سخت خشمگین شد ، فرمود اینطور سخن نگویید و مرا سید و مولا نخوانید بلکه بگویید پیغمبر ما و فرستاده ی خدای ما ، سخن به راستی و حقیقت بگویید و در گفتار خود زیاده روی و غلو نکنید که گرفتار ضلالت و گمراهی خواهید شد.

منبع : جعفر پات ص184

27- روزی حضرت امام علی (علیه السّلام) بر مرکب سوار شد، جمعی پیاده به پشت سرش به راه افتادند، حضرت به آنها فرمود : مگر نمی دانید پیاده روی مردم در رکاب سوار باعث فساد اخلاق سوار و ذلت و خواری پیادگان است، برگردید و به راه خود بروید.

منبع : تحف العقول ص209

28- حضرت امام علی (علیه السّلام) در راه مسافرت شام با سربازان خود به شهر انبار آمد. در خارج شهر، مردم به رسم و آیین دوره ی ساسانیان کنار جاده زیر آفتاب به انتظار ایستاده بودند، موقعیکه رئیس مملکت به صف مستقبلین رسید، کدخدایان و تجار و بزرگان شهر یکباره به سوی آن حضرت هجوم بردند و در رکابش پیاده شروع کردند به دویدن. حضرت امام علی (علیه السّلام) از مشاهده ی این حرکت وهن آور و ذلّت بار، که منافی با آزادگی و شرافت اسلامی بود،سخت ناراحت شد و پرسید این چه کاری بود که کردید؟ گفتند: این رسم و روش ما است که به منظوربزرگداشت امرا و فرمانروایان خود انجام می دهیم. حضرت امام علی (علیه السّلام) آن روش تحقیر آمیز را به شدت نکوهش کرد و فرمود امرا و زمامدارانتان از این کار بهره ای نمی برند ولی شما با این عمل موهن، خویشتن را در دنیا به رنج و مشقت می اندازید و خود را حقیر و خوار می سازید. به علاوه در آخرت نیز عذاب و مشقت خواهید داشت و برای تن دادن به پستی و ذلت کیفر خواهید شد. سپس فرمود: چه زیان آور است مشقتی که آدمی از پی آن عذاب و کیفر بیند و چه پر منفعت است آسودگی و آرامشی که با آن ایمنی از عذاب الهی باشد.

منبع : نهج البلاغه ،کلمه ی 36

29- موقعیکه رسول اکرم (صلّی الله علیه و آله و سلّم) سواره حرکت می کرد اجازه نمی داد کسی با او پیاده راه برود مگر آنکه او را به ترک خود سوار کند و اگر پیاده از سوار شدن خودداری می نمود به وی می فرمودند شما بیشتر بروید و در مکان مورد نظر یکدیگر را ملاقات خواهیم کرد.

منبع : بحار ،ص153

30- ابی بصیر به حضرت امام صادق (علیه السّلام) عرض کرد: مردی کم بضاعت با افراد متمکن و ثروتمند رفیق سفر می شود. آنان با ثروت بسیاری که دارند آزادانه مصارف مسافرت را می پردازند ولی او قادر نیست مانند آنها خارج کند. امام فرمودند: دوست ندارم که خود را ذلیل و پست نماید ، البته با کسانی رفیق راه شود که در ثروت همانند وی هستند.

منبع : مکارم اخلاق ، ص131

31- حضرت امام محمدباقر (علیه السّلام) فرموده اند: با اقران و امثال خود مصاحبت کن و با کسانیکه مساعدت و کمک آنان بی نیازت میسازد رفاقت مکن چه این کار مایه ی ذلت و خواری است.

منبع : مکارم الاخلاق ،ص131

32- حضرت امام صادق (علیه السّلام) فرموده اند: شایسته نیست مؤمن ، خویش را ذلیل و خوار نماید. راوی سؤال می کند چگونه خود را ذلیل می کند؟ حضرت در جواب فرمود در امری مداخله می نماید که شایسته ی آن نیست و سرانجام باید از آن عذر بخواهد.

منبع : کافی جلد 5 ص64

33- حضرت امام صادق (علیه السّلام) فرموده اند: سزاوار نیست مرد با ایمان موجبات خواری و ذلت را فراهم نماید. عرض شد چگونه آدمی باعث خواری خود می شود؟ فرمود به کاری دست می زند که قدرت و طاقت انجام آن را ندارد.

منبع : سفینه (طمع) ص 93

پستی و فرومایگی

34- حضرت امام علی (علیه السّلام) فرموده اند: آنکس که خویشتن را پست و فرومایه بداند به خیر و نیکی او امیدوار نباش.

منبع: غررالحکم ص 712

35- حضرت امام هادی (علیه السّلام) فرموده اند: کسی که خود را کوچک و موهون بداند و در خود احساس حقارت کند خویشتن را از شر او در امان ندان.

منبع: بحار جلد 17 ص 214

36- حضرت امام علی (علیه السّلام) فرموده اند: زبان مردم فرومایه و بی شخصیت بر آنان حکومت می کند، هرچه می خواهند می گویند و از گفته های ناروای خود، به علت حقارت نفس، احساس شرمساری نمی کنند.

منبع: نهج البلاغه فیض ص 1079

37- رسول اکرم (صلّی الله علیه و آله و سلّم) فرموده اند: وقتی گناهکاران، سرور مردم شوند و فرومایگان پست، رؤسا مردم باشند و در جامعه به بدکاران احترام شود، باید در آنجا منتظر بلا و بدبختی بود.

منبع: بحار جلد 17 ص 41

38- حضرت امام علی (علیه السّلام) فرموده اند: موقعی که فرومایگان در بین مردم سروری و بزرگی بدست آورند آروزی خوشبختی و سعادت آن جامعه از میان می رود و درهای ترقی و تعالی به روی مردم، بسته می شود.

منبع: غررالحکم ص 412-427

39- حضرت امام علی (علیه السّلام) فرموده اند: کارهای بزرگ را به مردم پست و فرومایه سپردن باعث زوال دولتها است.

منبع: غررالحکم ص 412-427

40- حضرت امام صادق (علیه السّلام) روش برتری طلبان خشن و خودخواه را و همچنین رفتار مهرطلبان زبون و پست را مطرود شناخته و ضمن سخنان خود به عبدالله بن جندب فرموده اند: نه بداخلاق و تندخو باش که مردم به ملاقاتت بی رغبت باشند و از تو دوری گزینند و نه پست و فرومایه باش که آشنایانت تو را با دیده ی تحقیر بنگرند و آنانکه تو را می شناسند خوارت بدارند.

منبع: تحف العقول، ص 304

41- روزی حضرت علی (علیه السّلام) بر مرکب سوار شد و کسانی پیاده در رکابش به راه افتادند. حضرت عنان کشید و فرمودند: مگر نمی دانید پیاده روی افراد در رکاب سوار، باعث فساد اخلاق راکب و مایه ی ذالت و خواری پیادگان است. برگردید و پیاده با من نیایید.

منبع: تحف العقول،ص209

 

www.ez12.persianblog.ir

با تشکر از انتخاب شما

Introduction to Chain of Responsibility

In this article, we’ll explain and demonstrate the Chain of Responsibility pattern.

Definition

The Chain of Responsibility is a behavioral design pattern that processes a request through a series of processor (handlers/receivers) objects. The request is sent from one handler object to another and processed by one (pure implementation) or all of the handlers. All the handlers are part of the chain.

Two simple examples containing a chain logic are:

  • a person using an ATM to get cash, (enter pin, amount, receipt);
  • a help desk call (options list, press dial buttons, follow the steps).

Participants

The pattern in the short version includes:

  • The Handler: defines an interface for handling requests. It can be an abstract class, which optionally implements default methods and the way to set a successor in the chain.
  • Many concrete handler objects: process the request and optionally provide access to successors;

CoR can also include:
– a Client object to perform the request and set up the chain;
– a Request object;
– a Response object;
– other design patterns.

The CoR design pattern is not one that is used often, but its core logic makes it useful in several cases.

CoR is useful when:

  • the handler must be determined automatically (e.g., a logging system);
  • the handler cannot be known in advance (e.g., handling exceptions);
  • the request must pass through a specific chain’s priority (e.g., event propagation, command propagation) or the order of the chain must be dynamic.

Basic usage

CoR is often applied in conjunction with Composite pattern, so it’s easy to treat all the handlers in the same way and dispatch the request to the chain’s successors.
Below is a basic PHP example:

<?php
abstract class BasicHandler
{
    /**
     * @var Handler
     */
    private $successor = null;

    /**
     * Sets a successor handler.
     * 
     * @param Handler $handler
     */
    public function setSuccessor(Handler $handler)
    {
        $this->successor = $handler;
    }

    /**
     * Handles the request and/or redirect the request
     * to the successor.
     *
     * @param mixed $request
     *
     * @return mixed
     */
    abstract public function handle($request);

}

Below is an example (not fully implemented) continuing with the code above:

class FirstHandler extends BasicHandler
{
    public function handle($request)
    {
        //provide a response, call the next successor
    }
}

// .. code for SecondHandler and ThirdHandler classes ..

$firstHandler = new FirstHandler();
$secondHandler = new SecondHandler();
$thirdHandler = new ThirdHandler();

$firstHandler->setSuccessor($secondHandler);
$secondHandler->setSuccessor($thirdHandler);

$result = $firstHandler->handle($request);

Advanced usage

The power behind this pattern is the flexibility and the open logic in the chain organization.
This flexibility becomes clearer with some examples.

From the BasicHandler code, it’s possible to automate the handle method (with some constraints) moving its scope from the children to the parent abstract class.

While the example below doesn’t solve all the CoR issues, it shows how the pattern can be easily restructured and adapted to different logic.

<?php
abstract class AdvancedHandler
{
    /**
     * @var Handler
     */
    private $successor = null;

    /**
     * Sets a successor handler,
     * in case the class is not able to satisfy the request.
     *
     * @param Handler $handler
     */
    final public function setSuccessor(Handler $handler)
    {
        if ($this->successor === null) {
            $this->successor = $handler;
        } else {
            $this->successor->setSuccessor($handler);
        }
    }

    /**
     * Handles the request or redirect the request
     * to the successor, if the process response is null.
     *
     * @param string|array $data
     *
     * @return string
     */
    final public function handle($request)
    {
        $response = $this->process($request);
        if (($response === null) && ($this->successor !== null)) {
            $response = $this->successor->handle($request);
        }

        return $response;
    }

    /**
     * Processes the request.
     * This is the only method a child can implements, 
     * with the constraint to return null to dispatch the request to next successor.
     * 
     * @param $request
     *
     * @return null|mixed
     */
    abstract protected function process($request);
}

class FirstHandler extends AdvancedHandler
{
    public function process($request)
    {
        //do something
    }
}

// .. code for SecondHandler and ThirdHandler classes ..
$firstHandler = new FirstHandler();
$secondHandler = new SecondHandler();
$thirdHandler = new ThirdHandler();

//the code below sets all successors through the first handler
$firstHandler->setSuccessor($secondHandler);
$firstHandler->setSuccessor($thirdHandler);

$result = $firstHandler->handle($request);

The example above minimizes the methods inside the Concrete Handler (increasing the cohesion) despite the constraint on a not null response.

If it’s necessary to go to the end of the chain for each request, it’s easy to refactor the handle method returning the response when the successor is null, because the last chain’s handler doesn’t have a successor. It is also possible to use a more structured Response object.

There are several modifications to the CoR – for example, combining this pattern with others, like the Factory or Decorator pattern to obtain an incremental construction/change of the Response.

Real world examples include the making of a car (chassis, interior, exterior, painting, wheels, etc.), or the creation of a web page (header, body, content, and footer).

I encourage you to explore other pattern modifications.

Next, we’ll look at some suggestions on common CoR issues like configuring the priority and speeding up the chain.

Configuring the chain

Extracting the logic for configuring the chain’s handlers helps keep the code clean and allows for easy changes.

Using a configuration object with Dependency Injection we can make the configuration global (e.g. via a yaml file).

class Client
{
    private $firstHandler;
    
    public function setChainOrder($handlersOrder)	
    {
        //code for setup the chain
    }
    public function process($request)
    {
        $response = $this->firstHandler->handle($request);
        
        return $response; 
    }
}
$client = new Client();
$client->setChainOrder($myHanldersOrder);
$client->process($request);

Dependency Injection can allow for more flexibility. For example, the chain can be configured by each Request object, as in the example below, with a little code modification.

$client = new Client();
$handlersOrder = $request->getHandlersOrder();
$client->setChainOrder($handlersOrder);
$client->process($request);

Speeding up the chain

If the CoR is stressed by several requests and the handlers are also complex – maybe they create other classes to process the request – a Service Container could be useful.

A Service Container (or dependency injection container) that manages the instantiation of objects without creating them each time helps improve memory and performance.

If CoR receives the same type of request often, a caching system is useful for improving speed.
One possible solution is to use an implementation of the Flyweight Pattern to store responses and provide the stored response (if it exists) on identical requests, without having to process the chain again.

In this example, I have added a simple cache to the AdvancedHandler class.

abstract class AdvancedHandler
{
//code ...
    final public function handle($request)
    {
        $response = $this->cache->getResponse($request);
        if ($response === null) {
            $response = $this->handleRequestWithChain($request);    
        }
        
        return $response;
    }   

    final public function handleRequestWithChain($request)
    {
        $response = $this->process($request);
        if (($response === null) && ($this->successor !== null)) {
            $response = $this->successor->handleRequestWithChain($request);
        }
        $this->cache->setResponse($response);

        return $response;
    }
//code ...    
}

Final thoughts

The Chain of Responsibility can be a very powerful pattern. It is also possible to implement a chain of chains, making a multidimensional structure.

CoR promotes loose coupling: every handler could be changed (or removed) without a big impact on the whole structure, but its flexibility, with a wrong design, can cause problems on all the chain’s objects involved.

I advise you to make a thorough analysis of the problem you are trying to solve before implementing the CoR pattern, and pay attention to the definition of the handler (abstract class or interface), the request, the response and their interactions.

OOP In JavaScript: What You NEED to Know

(Object Oriented JavaScript: Only Two Techniques Matter)

Prerequisite:
JavaScript Objects in Detail
JavaScript Prototype

Object Oriented Programming (OOP) refers to using self-contained pieces of code to develop applications. We call these self-contained pieces of code objects, better known as Classes in most OOP programming languages and Functions in JavaScript. We use objects as building blocks for our applications. Building applications with objects allows us to adopt some valuable techniques, namely, Inheritance (objects can inherit features from other objects), Polymorphism (objects can share the same interface—how they are accessed and used—while their underlying implementation of the interface may differ), and Encapsulation (each object is responsible for specific tasks).

Our Career Paths and Courses Website Is Now Live

New UPDATE: June 8, 2015

Enrollment for our Career Paths is well underway. Enroll now. Career Path 1: Junior JavaScript Developer and Career Path 3: Modern Frontend Developer are already full (you may still get a spot if you join the wait list now).

The second cohort for Career Path 5: Modern Fullstack Developer is also full. The second cohort starts immediately after the first cohort of Career Path 3 graduates.

https://learn.modern-developer.com

In this article, we are concerned with only Inheritance and Encapsulation since only these two concepts apply to OOP in JavaScript, particularly because, in JavaScript, objects can encapsulate functionalities and inherit methods and properties from other objects. Accordingly, in the rest of the article, I discuss everything you need to know about using objects in JavaScript in an object oriented manner—with inheritance and encapsulation—to easily reuse code and abstract functionalities into specialized objects.

We will focus on only the best two techniques1 for implementing OOP in JavaScript. Indeed, many techniques exist for implementing OOP in JavaScript, but rather than evaluate each, I choose to focus on the two best techniques: the best technique for creating objects with specialized functionalities (aka Encapsulation) and the best technique for reusing code (aka Inheritance). By “best” I mean the most apt, the most efficient, the most robust.

Encapsulation and Inheritance Overview

Objects can be thought of as the main actors in an application, or simply the main “things” or building blocks that do all the work. As you know by now, objects are everywhere in JavaScript since every component in JavaScript is an Object, including Functions, Strings, and Numbers. We normally use object literals or constructor functions to create objects.

Encapsulation refers to enclosing all the functionalities of an object within that object so that the object’s internal workings (its methods and properties) are hidden from the rest of the application. This allows us to abstract or localize specific set of functionalities on objects.

Inheritance refers to an object being able to inherit methods and properties from a parent object (a Class in other OOP languages, or a Function in JavaScript).

Both of these concepts, encapsulation and inheritance, are important because they allow us to build applications with reusable code, scalable architecture, and abstracted functionalities. Maintainable, scalable, efficient.


An instance is an implementation of a Function. In simple terms, it is a copy (or “child”) of a Function or object. For example:

// Tree is a constructor function because we will use new keyword to invoke it.
function Tree (typeOfTree) {} 

// bananaTree is an instance of Tree.
var bananaTree = new Tree ("banana");

In the preceding example, bananaTree is an object that was created from the Tree constructor function. We say that the bananaTree object is an instance of the Tree object. Tree is both an object and a function, because functions are objects in JavaScript. bananaTree can have its own methods and properties and inherit methods and properties from the Tree object, as we will discuss in detail when we study inheritance below.

OOP in JavaScript

The two important principles with OOP in JavaScript are Object Creation patterns (Encapsulation) and Code Reuse patterns (Inheritance). When building applications, you create many objects, and there exist many ways for creating these objects: you can use the ubiquitous object literal pattern, for example:

var myObj = {name: "Richard", profession: "Developer"}; 

You can use the prototype pattern, adding each method and property directly on the object’s prototype. For example:


function Employee () {}

Employee.prototype.firstName = "Abhijit";
Employee.prototype.lastName = "Patel";
Employee.prototype.startDate = new Date();
Employee.prototype.signedNDA = true;
Employee.prototype.fullName = function () {
console.log (this.firstName + " " + this.lastName); 
};

var abhijit = new Employee () //
console.log(abhijit.fullName()); // Abhijit Patel
console.log(abhijit.signedNDA); // true

You can also use the constructor pattern, a constructor function (Classes in other languages, but Functions in JavaScript). For example:


function Employee (name, profession) {
this.name = name;
this.profession = profession;
} // Employee () is the constructor function because we use the new keyword below to invoke it.

var richard = new Employee (“Richard”, “Developer”) // richard is a new object we create from the Employee () constructor function.

console.log(richard.name); //richard
console.log(richard.profession); // Developer

In the latter example, we use a custom constructor function to create an object. This is how we create objects when we want to add methods and properties on our objects, and when we want to encapsulate functionality on our objects. JavaScript developers have invented many patterns (or ways) for creating objects with constructor functions. And when we say Object Creation Patterns, we are concerned principally with the many ways of creating objects from constructor functions, as in the preceding example.

In addition to the patterns for creating objects, you want to reuse code efficiently. When you create your objects, you will likely want some of them to inherit (have similar functionality) methods and properties from a parent object, yet they should also have their own methods and properties. Code reuse patterns facilitate ways in which we can implement inheritance.

These two universal principles—creating objects (especially from constructor Functions) and allowing objects to inherit properties and methods—are the main focus of this article and, indeed, the main concepts with OOP in JavaScript. We first discuss the object creation pattern.

Encapsulation in JavaScript

(The Best Object Creation Pattern: Combination Constructor/Prototype Pattern)

As discussed above, one of the main principles with OOP is encapsulation: put all the inner workings of an object inside that object. To implement encapsulation in JavaScript, we have to define the core methods and properties on that object. To do this, we will use the best pattern for encapsulation in JavaScript: the Combination Constructor/Prototype Pattern. This name is a mouthful, but you needn’t memorize it, since we are only concerned with its implementation. Before we implement it, let’s quickly learn a bit more about the practicality of encapsulation.

Why Encapsulation?
When you simply want to create an object just to store some data, and it is the only object of its kind, you can use an object literal and create your object. This is quite common and you will use this simple pattern often.

However, whenever you want to create objects with similar functionalities (to use the same methods and properties), you encapsulate the main functionalities in a Function and you use that Function’s constructor to create the objects. This is the essence of encapsulation. And it is this need for encapsulation that we are concerned with and why we are using the Combination Constructor/Prototype Pattern.

To make practical use of OOP in JavaScript, we will build an object-oriented quiz application that uses all the principles and techniques we learn in this article. First up, our quiz application will have users (a Users Function) who take the quiz. There will be some common properties for every user who takes the quiz: each user will have a name, a score, an email, and the quiz scores (all the scores). These are the properties of the User object. In addition, each User object should be able to show the name and score, save scores, and change the email. These are the methods of the object.

Because we want ALL the user objects to have these same properties and methods, we cannot use the object literal way of creating objects. We have to use a constructor Function to encapsulate these properties and methods.

Since we know all users will have the same set of properties, it makes sense to create a Function (Class in OOP languages) that encapsulates these properties and methods. Thus, we will use the Combination Constructor/Prototype Pattern for this.

Implementation of Combination Constructor/Prototype Pattern
The User Function:

I will explain each line.

function User (theName, theEmail) {
    this.name = theName;
    this.email = theEmail;
    this.quizScores = [];
    this.currentScore = 0;
}

User.prototype = {
    constructor: User,
    saveScore:function (theScoreToAdd)  {
        this.quizScores.push(theScoreToAdd)
    },
    showNameAndScores:function ()  {
        var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
        return this.name + " Scores: " + scores;
    },
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
}

Make Instances of the User function

// A User 
firstUser = new User("Richard", "Richard@examnple.com"); 
firstUser.changeEmail("RichardB@examnple.com");
firstUser.saveScore(15);
firstUser.saveScore(10); 

firstUser.showNameAndScores(); //Richard Scores: 15,10

// Another User
secondUser = new User("Peter", "Peter@examnple.com");
secondUser.saveScore(18);
secondUser.showNameAndScores(); //Peter Scores: 18

Explanation of Combination Constructor/Prototype Pattern
Let’s expound on each line of code so we have a thorough understanding of this pattern.

The following lines initialize the instance properties. These properties will be defined on each User instance that is created. So the values will be different for each user. The use of the this keyword inside the function specifies that these properties will be unique to every instance of the User object:

this.name = theName;
this.email = theEmail;
this.quizScores = [];
this.currentScore = 0;

In the code below, we are overwriting the prototype property with an object literal, and we define all of our methods (that will be inherited by all the User instances) in this object. Discussion continues after the code:

User.prototype = {
    constructor: User,
    saveScore:function (theScoreToAdd)  {
        this.quizScores.push(theScoreToAdd)
    },
    showNameAndScores:function ()  {
        var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
        return this.name + " Scores: " + scores;
    },
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }
}

This way of overwriting the constructor is simply for convenience, so we don’t have to write User.prototype each time, like this:


User.prototype.constructor = User;
User.prototype.saveScore = function (theScoreToAdd)  {
    this.quizScores.push(theScoreToAdd)
};

User.prototype.showNameAndScores = function ()  {
    var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
    return this.name + " Scores: " + scores;
};

User.prototype.changeEmail =  function (newEmail)  {
    this.email = newEmail;
    return "New Email Saved: " + this.email;
}

By overwriting the prototype with a new object literal we have all the methods organized in one place, and you can better see the encapsulation that we are after. And of course it is less code you have to type.

JavaScript Prototype
In JavaScript, you add methods and properties on the prototype property when you want instances of an object to inherit those methods and properties. This is the reason we add the methods on the User.prototype property, so that they can be used by all instances of the User object. Read more about JavaScript Prototype in Plain Language.

Constructor Property
In my post JavaScript Prototype, I explained that every function has a constructor property, and this property points to the constructor of the function. For example:

function Fruit () {}
var newFruit = new Fruit ();
console.log (newFruit.constructor) // Fruit ()

The one disadvantage of overwriting the prototype is that the constructor property no longer points to the prototype, so we have to set it manually. Hence this line:


constructor: User

Prototype Methods
In the following lines, we create methods on the prototype (in the object literal) so that all instances of Users can have access to these methods.

saveScore:function (theScoreToAdd)  {
        this.quizScores.push(theScoreToAdd)
    },
    showNameAndScores:function ()  {
        var scores = this.quizScores.length > 0 ? this.quizScores.join(",") : "No Scores Yet";
        return this.name + " Scores: " + scores;
    },
    changeEmail:function (newEmail)  {
        this.email = newEmail;
        return "New Email Saved: " + this.email;
    }

We then created instances of the User object:

// A User 
firstUser = new User("Richard", "Richard@examnple.com"); 
firstUser.changeEmail("RichardB@examnple.com");
firstUser.saveScore(15);
firstUser.saveScore(10); 

firstUser.showNameAndScores(); //Richard Scores: 15,10

// Another User
secondUser = new User("Peter", "Peter@examnple.com");
secondUser.saveScore(18);
secondUser.showNameAndScores(); //Peter Scores: 18

As you see, we have encapsulated all the functionality for a User inside the User Function, so that each instance of User can make use of the prototype methods (like changeEmail) and define their own instance properties (like name and email).

With this pattern, you can use the standard operators and methods on the instances, including the instanceOf operator, the for-in loop (even hasOwnProperty), and the constructor property.

Inheritance in JavaScript

(The Best Pattern: Parasitic Combination Inheritance)

Implementing inheritance in our quiz application will permit us to inherit functionality from parent Functions so that we can easily reuse code in our application and extend the functionality of objects. Objects can make use of their inherited functionalities and still have their own specialized functionalities.

The best pattern for implementing inheritance in JavaScript is the Parasitic Combination inheritance 2. Before we dive into this awesome pattern, let’s see why its practical to use inheritance in our applications.

We have successfully implemented encapsulation by enclosing all the functionality for users of our quiz application by adding all the methods and properties that each user will need on the User function, and all instances of User will have those properties and methods.

Why Inheritance?

Next, we want to encapsulate all the functionalities for every Question. The Question function (Class in OOP languages) will have all the generic properties and methods that every kind of question will need to have. For example, every question will have the question, the choices, and the correct answer. These will be the properties. In addition, each question will have some methods: getCorrectAnswer and getUserAnswer, and displayQuestion.

We want our quiz application to make different types of Questions. We will implement a MultipleChoiceQuestion function and a DragDropQuestion function. To implement these, it would not make sense to put the properties and methods outlined above (that all questions will use) inside the MultipleChoiceQuestion and DragDropQuestion functions separately, repeating the same code. This would be redundant.

Instead, we will leave those properties and methods (that all questions will use) inside the Question object and make the MultipleChoiceQuestion and DragDropQuestion functions inherit those methods and properties. This is where inheritance is important: we can reuse code throughout our application effectively and better maintain our code.

Since the MultipleChoiceQuestion HTML layout and will be different from the DragDropQuestion HTML layout, the displayQuestion method will be implemented differently in each. So we will override the displayQuestion method on the DragDropQuestion. Overriding functions is another principle of OOP.

Lets Code.

Implementing the Parasitic Combination Inheritance Pattern

To implement this pattern, we have to use two techniques that were invented specifically for inheritance in JavaScript. Some notes about these techniques follow. No need to memorize any of the detail; just understand and be aware of the techniques.

Prototypal Inheritance by Douglas Crockford

Douglas Crockford created the following Object.create method 3, used in a fundamental way to implementing inheritance with the pattern we are using.

Object.create method
Ruminate on the method Crockford created:

 if (typeof Object.create !== 'function') {
    Object.create = function (o) {
        function F() {
        }

        F.prototype = o;
        return new F();
    };
}

This method has been added to the ECMAScript5 specification, and you can access it with Object.create (). Let’s quickly understand it is doing.

Object.create = function (o) {
//It creates a temporary constructor F()
        function F() {
        }
//And set the prototype of the this constructor to the parametric (passed-in) o object
//so that the F() constructor now inherits all the properties and methods of o
        F.prototype = o;

//Then it returns a new, empty object (an instance of F())
//Note that this instance of F inherits from the passed-in (parametric object) o object. 
//Or you can say it copied all of the o object's properties and methods
        return new F();
    }

The crux of the matter with this Object.create method is that you pass into it an object that you want to inherit from, and it returns a new object that inherits from the object you passed into it. For example:

// We have a simple cars object
var cars = {
    type:"sedan",
    wheels:4
};

// We want to inherit from the cars object, so we do:
var toyota = Object.create (cars); // now toyota inherits the properties from cars
console.log(toyota.type); // sedan

Of course we can now add more properties to the toyota object, but let’s move on.

The next function we will use for inheritance is the inheritPrototype function. This function succinctly implements the parasitic combination inheritance for us. We pass in the parent object (or Super Class) and the child object (or Sub Class), and the function does the parasitic combination inheritance: makes the child object inherits from the parent object.

 function inheritPrototype(childObject, parentObject) {
    // As discussed above, we use the Crockford’s method to copy the properties and methods from the parentObject onto the childObject
// So the copyOfParent object now has everything the parentObject has 
    var copyOfParent = Object.create(parentObject.prototype);

    //Then we set the constructor of this new object to point to the childObject.
// Why do we manually set the copyOfParent constructor here, see the explanation immediately following this code block.
    copyOfParent.constructor = childObject;

    // Then we set the childObject prototype to copyOfParent, so that the childObject can in turn inherit everything from copyOfParent (from parentObject)
   childObject.prototype = copyOfParent;
}

Why did we manually set the copyOfParent.constructor?
________________________________________
We explicitly set the copyOfParent.constructor property to point to the childObject constructor because in the preceding step, var copyOfParent = Object.create(parentObject.prototype), this is what we actually did:

// We made a new object and overwrote its prototype with the parentObject prototype:
function F() {
        }
F.prototype = parentObject.prototype;
// Then it was this new F object we assigned to copyOfParent.
// All of this was done inside the Object.create () method.

So, this new F object, which we assigned to copyOfParent, doesn’t have a constructor property anymore because we overwrote its entire prototype. Whenever you overwrite an object’s prototype (object.prototype = someVal), you also overwrite the object’s constructor property.

To make sure we have the correct value for copyOfParent constructor, we set it manually with this:
copyOfParent.constructor = childObject;

A commenter by the name of John correctly pointed our that I did not corruptly explain this bit, hence this detailed explanation.
________________________________________

Essentially, we are copying all the properties and methods from the parentObject to the childObject, but we are using the copyOfParent as an intermediary for the copy. And because the childObject prototype was overwritten during the copy, we manually set the copyOfParent constructor to the childObject. Then we set the childObject prototype to the copyOfParent so that the childObject inherits from the parentObject.

Okay, that was quite a bit. I am hopeful you understand some of that :).

Back to the fun stuff: Creating our quiz OOP style.
Now that we understand the inheritPrototype function we will be using, lets go ahead and implement our Question constructor.

Note that I use “constructor” and “function” interchangeably sometimes in this particular article when referring to the function, because the function will be used as a constructor to create instances.

The Question Constructor (Parent of all Question Objects):
(Can be thought of as the Super Class for Questions)

 // The Question function is the parent for all other question objects;
// All question objects will inherit from this Question constructor

function Question(theQuestion, theChoices, theCorrectAnswer) {
    // Initialize the instance properties
    this.question = theQuestion;
    this.choices = theChoices;
    this.correctAnswer = theCorrectAnswer;
    this.userAnswer = "";

    // private properties: these cannot be changed by instances
    var newDate = new Date(),
    // Constant variable: available to all instances through the instance method below. This is also a private property.
        QUIZ_CREATED_DATE = newDate.toLocaleDateString();

// This is the only way to access the private QUIZ_CREATED_DATE variable 
// This is an example of a privilege method: it can access private properties and it can be called publicly
    this.getQuizDate = function () {
        return QUIZ_CREATED_DATE;
    };

// A confirmation message that the question was created
    console.log("Quiz Created On: " + this.getQuizDate());

}

Add Prototype Methods to The Question Object
All instances of the Question object will inherit these methods, because we are adding the methods on the Question prototype.

 // Define the prototype methods that will be inherited
Question.prototype.getCorrectAnswer = function () {
    return  this.correctAnswer;
};

Question.prototype.getUserAnswer = function () {
    return this.userAnswer;
};

Question.prototype.displayQuestion = function () {
    var questionToDisplay = "<div class='question'>" + this.question + "</div><ul>";
        choiceCounter = 0;

    this.choices.forEach(function (eachChoice)  {
        questionToDisplay += '<li><input type="radio" name="choice" value="' + choiceCounter + '">' + eachChoice + '</li>';
        choiceCounter++;
    });
    questionToDisplay += "</ul>";

    console.log (questionToDisplay);
}; 

Child Questions (Sub Classes of the Question object)
Now that we have the Question constructor object setup, we can inherit from it and create sub classes (children objects). The power of inheritance is that we can create all sorts of questions now, and each can be quite versatile.

First, a Multiple Choice Question:

// Create the MultipleChoiceQuestion
function MultipleChoiceQuestion(theQuestion, theChoices, theCorrectAnswer){
// For MultipleChoiceQuestion to properly inherit from Question, here inside the MultipleChoiceQuestion constructor, we have to explicitly call the Question constructor
// passing MultipleChoiceQuestion as the this object, and the parameters we want to use in the Question constructor:
    Question.call(this, theQuestion, theChoices, theCorrectAnswer);
};

And then we have to use the inheritPrototype function we discussed moments ago:

// inherit the methods and properties from Question
inheritPrototype(MultipleChoiceQuestion, Question);

After we have inherited from Question, we then add methods to the MultipleChoiceQuestion function, if necessary. But we must do it after we inherit, not before, or all the methods we define on its prototype will be overwritten. We are not adding any now.

A Drag and Drop Question
In a similar manner, we can make yet another type of question:

// Create the DragDropQuestion
function DragDropQuestion(theQuestion, theChoices, theCorrectAnswer) {
    Question.call(this, theQuestion, theChoices, theCorrectAnswer);
}

// inherit the methods and properties from Question
inheritPrototype(DragDropQuestion, Question);

Overriding Methods
Overriding methods is a another principle of OOP, and we can do it easily with this pattern. Since the Drag and Drop questions will have a different HTML layout from the Multiple Choice questions (no radio buttons, for example), we can override the displayQuestion method so it operates specifically to the Drag and Drop question needs:

// Override the displayQuestion method it inherited
DragDropQuestion.prototype.displayQuestion = function () {
    // Just return the question. Drag and Drop implementation detail is beyond this article
    console.log(this.question);
};

In our real Quiz application, we would create a Quiz constructor that is the main application that launches the quiz, but in this article, we can test our inheritance code by simply doing this:

// Initialize some questions and add them to an array
var allQuestions = [
new MultipleChoiceQuestion("Who is Prime Minister of England?", ["Obama", "Blair", "Brown", "Cameron"], 3),
   
new MultipleChoiceQuestion("What is the Capital of Brazil?", ["São Paulo", "Rio de Janeiro", "Brasília"], 2),
   
new DragDropQuestion("Drag the correct City to the world map.", ["Washington, DC", "Rio de Janeiro", "Stockholm"], 0)
];

// Display all the questions
allQuestions.forEach(function (eachQuestion)  {
    eachQuestion.displayQuestion();
});

If you run the code, you will see that the displayQuestion for the multiple choice questions returns the question in a div tag, with choices formatted with radio buttons inside li tags. On the other hand, the drag and drop questions displayQuestion method simply returns the question without the choices.

Nicholas Zakas stated it wonderfully, “Parasitic combination inheritance is considered the most optimal inheritance paradigm” 5 in JavaScript. If you learn it and understand it well, you should use it in your JavaScript web applications.

You might be wondering how is the Combination Constructor/Prototype Pattern we used for Encapsulation earlier different from the Parasitic Combination Inheritance. They are similar, but the former is best used for encapsulation (creating custom objects), and it does not have all the inheritance mechanisms such as subclassing (creating child constructors that inherit from the parent constructor). Moreover, the inheritance pattern goes beyond setting up objects to just inherit properties and methods, it enables child objects to themselves be parent objects of other objects, and you can use private members, overriding, and other OOP concepts.

Final Words

I gave you the full details for implementing the best two patterns for OOP in JavaScript, and I am hopeful you understood at least the general concepts. Go use these patterns in your JavaScript applications. Note that you can use OOP in even small and medium applications, not just complex applications.

Be good and do good work, and take care of yourself: sleep well, eat well, and enjoy life.

Further Reading

Read chapters 6 and 7 of Zakas’s Professional JavaScript for Web Developers.
Read chapters 5 and 6 of Stefanov’s JavaScript Pattens.
Read chapter 4 of Herman’s Effective JavaScript.

Notes

  1. Professional JavaScript for Web Developers Chapter 6.
  2. JavaScript Patterns Chapters 5 and 6
  3. Effective JavaScript: 68 Specific Ways to Harness the Power of JavaScript Chapter 4.
  4. http://javascript.crockford.com/prototypal.html
  5. Professional JavaScript for Web Developers Chapter 6, page 215.

Understanding process.nextTick()

I have seen quite a few people being confused about process.nextTick(). Let's take a look at what process.nextTick() does, and when to use it.

As you might already know, every Node application runs on a single thread. What this means is that apart from I/O - at any time, only one task/event is processed by Node's event loop. You can imagine this event loop to be a queue of callbacks that are processed by Node on every tick of the event loop. So, even if you are running Node on a multi-core machine, you will not get any parallelism in terms of actual processing - all events will be processed only one at a time. This is why Node is a great fit for I/O bound tasks, and definitely not for CPU intensive tasks. For every I/O bound task, you can simply define a callback that will get added to the event queue. The callback will fire when the I/O operation is done, and in the mean time, the application can continue to process other I/O bound requests.

Given this model, what process.nextTick() actually does is defer the execution of an action till the next pass around the event loop. Let's take a simple example. If we had a function foo() which we wanted to invoke in the next tick, this is how we do it:

function foo() {
    console.error('foo');
}

process.nextTick(foo);
console.error('bar');

If you ran the above snippet, you will notice that bar will be printed in your console before foo, as we have delayed the invokation of foo() till the next tick of the event loop:

bar
foo

In fact, you can get the same result by using setTimeout() this way:

setTimeout(foo, 0);
console.log('bar');

However, process.nextTick() is not just a simple alias to setTimeout(fn, 0) - it's far more efficient.

More precisely, process.nextTick() defers the function until a completely new stack. You can call as many functions as you want in the current stack. The function that called nextTick has to return, as well as its parent, all the way up to the root of the stack. Then when the event loop is looking for a new event to execute, your nextTick'ed function will be there in the event queue and execute on a whole new stack.

Let's see where we can use process.nextTick():

Interleaving execution of a CPU intensive task with other events

Let's say we have a task compute() which needs to run almost continuously, and does some CPU intensive calculations. If we wanted to also handle other events, like serving HTTP requests in the same Node process, we can use process.nextTick() to interleave the execution of compute() with the processing of requests this way:

var http = require('http');

function compute() {
    // performs complicated calculations continuously
    // ...
    process.nextTick(compute);
}

http.createServer(function(req, res) {
     res.writeHead(200, {'Content-Type': 'text/plain'});
     res.end('Hello World');
}).listen(5000, '127.0.0.1');

compute();

In this model, instead of calling compute() recursively, we use process.nextTick() to delay the execution of compute() till the next tick of the event loop. By doing so, we ensure that if any other HTTP requests are queued in the event loop, they will be processed before the next time compute() gets invoked. If we had not used process.nextTick() and had simply called compute() recursively, the program would not have been able to process any incoming HTTP requests. Try it for yourself!

So, alas, we don't really get any magical multi-core parallelism benefits by using process.nextTick(), but we can still use it to share CPU usage between different parts of our application.

Keeping callbacks truly asynchronous

When you are writing a function that takes a callback, you should always ensure that this callback is fired asynchronously. Let's look at an example which violates this convention:

function asyncFake(data, callback) {        
    if(data === 'foo') callback(true);
    else callback(false);
}

asyncFake('bar', function(result) {
    // this callback is actually called synchronously!
});

Why is this inconsistency bad? Let's consider this example taken from Node's documentation:

var client = net.connect(8124, function() { 
    console.log('client connected');
    client.write('world!rn');
});

In the above case, if for some reason, net.connect() were to become synchronous, the callback would be called immediately, and hence the client variable will not be initialized when the it's accessed by the callback to write to the client!

We can correct asyncFake() to be always asynchronous this way:

function asyncReal(data, callback) {
    process.nextTick(function() {
        callback(data === 'foo');       
    });
}

When emitting events

Let's say you are writing a library that reads from a source and emits events that contains the chunks that are read. Such a library might look like this:

var EventEmitter = require('events').EventEmitter;

function StreamLibrary(resourceName) { 
    this.emit('start');

    // read from the file, and for every chunk read, do:        
    this.emit('data', chunkRead);       
}
StreamLibrary.prototype.__proto__ = EventEmitter.prototype;   // inherit from EventEmitter

Let's say that somewhere else, someone is listening to these events:

var stream = new StreamLibrary('fooResource');

stream.on('start', function() {
    console.log('Reading has started');
});

stream.on('data', function(chunk) {
    console.log('Received: ' + chunk);
});

In the above example, the listener will never get the start event as that event would be emitted by StreamLibrary immediately during the constructor call. At that time, we have not yet assigned a callback to the start event yet. Therefore, we would never catch this event! Once again, we can use process.nextTick() to defer the emit till the listener has had the chance to listen for the event.

function StreamLibrary(resourceName) {      
    var self = this;

    process.nextTick(function() {
        self.emit('start');
    });

    // read from the file, and for every chunk read, do:        
    this.emit('data', chunkRead);       
}

I hope that demystifies process.nextTick(). If I have missed out something, please do share in the comments.