1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

JSでコールバック関数を外に定義するときに使えるbind関数

Posted at

JSで無名関数を外に出すときに使えるbind関数

例えばnodeJSで書かれた以下のようなコードがあり、
start関数の引数に指定されている無名関数をonRequest()として外に定義したいとします。

var http = require('http');
var url = require('url');

var start = function(router) {
	http.createServer(function(req,res) {
	// routerにパスを渡す
	var pathname = url.parse(req.url).pathname;
	router.route(pathname)

	res.writeHead(200, {"Content-Type": "text/plain"});
	res.write("hey");
	res.end();
}).listen(8888);
	console.log('Server has started.');
};

exports.start = start;

無名関数にはrouterというオブジェクトを渡してあげないといけないけど、
reqやresという引数がすでにあるので onRequest(router) のような書き方では渡せません。

そこで、以下のようにbind関数を使うと引数を渡すことができます。

var http = require('http');
var url = require('url');

var onRequest = function(router,req,res) {    // 引数としてrouterを前に追加する
	// routerにパスを渡す
	var pathname = url.parse(req.url).pathname;
	router.route(pathname)

	res.writeHead(200, {"Content-Type": "text/plain"});
	res.write("hello");
	res.end();
};

var start = function(router) {
	http.createServer(onRequest.bind(this, router)).listen(8888);    // 関数のbind関数を使用してrouterを渡す
	console.log('Server has started.');
};

exports.start = start;
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?