0
0

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 3 years have passed since last update.

関数コンストラクタの記述方法

const func = new Function("a","b", "return a + b + d");

実験

関数宣言/コンストラクタで生成された関数は、ともにオブジェクトであり、コンストラクタであるか

instanceofで確認してみる

// スコープに注意!
let d = 99; //Functionをd
const fn1 = new Function("a","b", "return a + b + d");

function fn2(a,b){
	return a + b
}
const result = fn1(1,2);
console.log(result)
// オブジェクトであるかどうか
console.log(fn1 instanceof Object)
console.log(fn2 instanceof Object)
// 関数コンストラクタから生成されたものであるか
console.log(fn1 instanceof Function)
console.log(fn2 instanceof Function)

スクリーンショット 2022-09-05 16.45.05.png

注意すること1

→グローバルコンテキストにあるコンテキストを読み込んでしまう。

let d = 99; //Functionのd
const func = new Function("a","b", "return a + b + d");
この場合のスコープが
// d=99はFunction内で普通に反映されますよ

注意すること2

thisを反映させるには、newを2回行う

const func = new Function("a","b", "console.log(a + b)");
const obj = new func()

こんな感じです

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?