为什么第二种写法会报错:
fetch('xxx').then(res => res.json()); //ok fetch('xxx').then(Response.prototype.json.call); //TypeError: undefined is not a function
如果把 fetch 返回的 Stream 对象打印出来,用 Store as global variable 保存到变量 temp1 是可以正常使用 Response.prototype.json.call 的:
Response.prototype.json.call(temp1).then(console.log); //ok
问题已解决,需要给 call 绑定 this:
fetch('xxx').then(Function.call.bind(Response.prototype.json)); //ok
![]() | 1 bnrwnjyw 2020-12-28 12:34:28 +08:00 ![]() var a = Response.prototype.json.call console.log(a) // undefined 这样懂么 |
![]() | 2 lisianthus OP @bnrwnjyw 变量 a 打印出来是 call() { [native code] } ,undefined 是 console.log 的返回值 |
![]() | 3 bnrwnjyw 2020-12-28 12:42:36 +08:00 ![]() @lisianthus 你调用一下 a 就知道了。 |
![]() | 4 lisianthus OP @bnrwnjyw 原来如此,需要给 call 绑定 this,这样就没问题了:fetch('xxx').then(Function.call.bind(Response.prototype.json)) |
5 indev 2020-12-28 13:23:46 +08:00 这是可以继续执行 fetch 返回的函数吗? |
![]() | 6 lisianthus OP @indev 没明白你问的是什么,fetch 返回的是 Promise,Promise 中 resolve 的值为 fetch 获取的流对象,then 接收一个回调函数作为参数,回调函数接收到的参数即为 resolve 的流对象,可以使用这个回调函数来处理流对象 |
![]() | 7 indev 2020-12-28 14:37:26 +08:00 @lisianthus 我是想问如果 resolve 后的 object 包含一个函数体,Function call 会执行这个函数吗? XSS 那种。 |
![]() | 8 lisianthus OP |
![]() | 9 indev 2020-12-29 14:23:46 +08:00 @lisianthus 嗯,明白了,谢谢 |