From 5ef028d61f6c1543603cdacbe0f8a0f00d5957c0 Mon Sep 17 00:00:00 2001 From: Jake Champion Date: Thu, 9 Jul 2020 15:10:59 +0100 Subject: [PATCH] Throw a TypeError if Request or Response functions are called without `new` --- fetch.js | 7 +++++++ test/test.js | 10 ++++++++++ 2 files changed, 17 insertions(+) diff --git a/fetch.js b/fetch.js index 5a572046..ecd719f0 100644 --- a/fetch.js +++ b/fetch.js @@ -322,6 +322,10 @@ function normalizeMethod(method) { } export function Request(input, options) { + if (!(this instanceof Request)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') + } + options = options || {} var body = options.body @@ -414,6 +418,9 @@ function parseHeaders(rawHeaders) { Body.call(Request.prototype) export function Response(bodyInit, options) { + if (!(this instanceof Response)) { + throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.') + } if (!options) { options = {} } diff --git a/test/test.js b/test/test.js index 51e30a33..aff0b1e0 100644 --- a/test/test.js +++ b/test/test.js @@ -330,6 +330,11 @@ exercise.forEach(function(exerciseMode) { // https://fetch.spec.whatwg.org/#request-class suite('Request', function() { + test('called as normal function', function() { + assert.throws(function() { + Request('https://fetch.spec.whatwg.org/') + }) + }) test('construct with string url', function() { var request = new Request('https://fetch.spec.whatwg.org/') assert.equal(request.url, 'https://fetch.spec.whatwg.org/') @@ -612,6 +617,11 @@ exercise.forEach(function(exerciseMode) { return new Response(body) }) + test('called as normal function', function() { + assert.throws(function() { + Response('{"foo":"bar"}', {headers: {'content-type': 'application/json'}}) + }) + }) test('creates Headers object from raw headers', function() { var r = new Response('{"foo":"bar"}', {headers: {'content-type': 'application/json'}}) assert.equal(r.headers instanceof Headers, true)