Mock.js源码分析

351次阅读
没有评论

Mock.js拦截AJAX的原理是什么?

源码src/mock.js文件的58行:

var XHR
if (typeof window !== 'undefined') XHR = require('./mock/xhr')
Mock.mock = function(rurl, rtype, template) {
    // Mock.mock(template)
    if (arguments.length === 1) {
        return Handler.gen(rurl)
    }
    // Mock.mock(rurl, template)
    if (arguments.length === 2) {
        template = rtype
        rtype = undefined
    }
    // 拦截 XHR
    if (XHR) window.XMLHttpRequest = XHR
    Mock._mocked[rurl + (rtype || '')] = {
        rurl: rurl,
        rtype: rtype,
        template: template
    }
    return Mock
}

如果调用了Mock.mock方法,那么就用MockXMLHttpRequest替换XMLHttpRequest ,

如果使用继承的方式来实现可以不可以呢?

参考文档:

正文完
 0
wujingquan
版权声明:本站原创文章,由 wujingquan 于2023-09-10发表,共计890字。
转载说明:Unless otherwise specified, all articles are published by cc-4.0 protocol. Please indicate the source of reprint.
评论(没有评论)