繁体   English   中英

Javascript中函数实例、函数对象和函数输出的区别

[英]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.newKeytest ,因为您已经使用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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM