这有段不是特别懂。。 - CNode技术社区

这有段不是特别懂。。
发布于 13 年前 作者 cooldrine 5287 次浏览 最后一次编辑是 9 年前
http.get({ host: 'shapeshed.com' }, function(res) {
 console.log("Got a response from shapeshed.com");
 }).on('error', function(e) {
 console.log("There was an error from shapeshed.com");
 });
).on('error', function(e)

一个点,一个on,代表啥意思。。 function(e) 这回调函数在这里有麻用 = =

11 回复

监听 error 时间,收到事件后,执行匿名函数function(e){} e 是错误事件的参数

.表示调用对象的方法,onaddListener的别名,用于注册事件监听器的,eventEmitter.addListener('err', function (e) {})就是监听eventEmitter(事件发生器,这里就是http.get()方法返回的对象)的error事件,事件发生后你传递的匿名函数function (e) {}会被调用,并且会得到一个参数e

这么看: http.get().on(...).on(...),说明 http.get() 这个函数返回的对象有 on() 这个方法可以调,同时,on() 方法也返回对象本身,所以可以继续 on()

专业名词应该叫 链式调用。

分开写就是:

var a = http.get(...);

a.on(‘error’, func_err);

function func_err(e) { }

哦 thx!

那这个on是哪个对象的方法哦?

噢,不过分开写就不是异步了吧。。

是否异步跟是否分开写没关系。。。

把对象的每一个方法最后都return this就可以无限链下去,比如

var a={
 b:'bbb',
 c:function(){
 	//doSomething
 	return this;
 },
 d:function(){
 	//doAnotherThing
 	return this;
 }
}

这样就可以a.c().d().c().d()...etc 当然你举的例子是function,不过function也是对象,一样也可以有属性和方法,function是比较有趣的变量~~

http.get().on(...).on(...) : 函数式语言的标准用法。

回到顶部

AltStyle によって変換されたページ (->オリジナル) /