[英]Difference between function instance, function object and function output in Javascript
我是 JavaScript 的初学者,我无法弄清楚它的输出应该是什么。
有人可以解释一下吗?
const a = new RandomFunc('test'); const b = RandomFunc; const c = RandomFunc('test'); function RandomFunc(val) { this.newKey = val; } console.log(a.newKey) console.log(b.newKey); console.log(c.newKey);
a.newKey
是test
,因为您已经使用new
关键字和new RandomFunc('test');
创建了一个RandomFunc
对象new RandomFunc('test');
. 这使得a
RandomFunc
实例的属性newKey
正确设置为test
,因为该函数在您使用new
实例化它时被调用。 在 Javascript 中,一切都是对象,包括函数。
b.newKey
undefined
,因为您为b
提供了表示函数RandomFunc
的函数对象; 它试图访问它的属性newKey
,但它没有,因为函数在 JS 中没有属性newKey
,显然。
c.newKey
抛出 TypeError 异常,因为c
是 undefined :它等于函数RandomFunc
的输出。 但是,它没有返回值,因此它返回undefined
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.