为什么构造函数返回对象,而不是JavaScript中的原语? [英] Why do constructor functions return objects, but not primitives in JavaScript?

查看:139
本文介绍了为什么构造函数返回对象,而不是JavaScript中的原语?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



我知道,JavaScript构造函数不应该返回任何东西(因此:

但是考虑这个JavaScript:



<$ p

$ p> function Thing(){
return'';
}
var t = new Thing();
console.log(t,typeof t); // => Thing {}object

现在,如果你这样做:

  function Thing(){
return {hi:''};
}
var t = new Thing();
console.log(t,typeof t); // => Object {hi:}object

甚至:

  function Thing(){
this.a ='a';
return {hi:''};
}
var t = new Thing();
console.log(t,typeof t); // => Object {hi:}object

因此,为什么JavaScript中的构造函数返回对象,但不是原始的,如果你写这种代码?






这种行为也在< =http://stackoverflow.com/a/29006924/209232>这个SO回答,但没有解释。我还滚动过新的运营商 a> ECMAScript规范的一部分,以及其构建<



任何提示或知识(请用简体中文)?


4.3.4构造函数

因此, [[Construct]] 内部方法(通过 operator ),检查由 [[Call]]


13.2.2 [[Construct]]


  1. 结果是调用 F 的[[Call]]内部属性的结果, em> obs 作为 this 值,并将传递给[[Construct]]的参数列表作为 args 提供

  2. 如果类型结果 。 >

其实这是一个不变式:


[[Construct]]()




  • 返回值的类型必须是Object。 $ b


I'm trying to understand JavaScript's (or at least V8's) behaviour regarding constructor functions.

I know, JavaScript constructor functions should never return anything (so: undefined).

But consider this JavaScript:

function Thing() { 
  return '';
}
var t = new Thing();
console.log(t, typeof t); // => Thing {} "object"

Now, if you do this:

function Thing() { 
  return { hi: '' };
}
var t = new Thing();
console.log(t, typeof t); // => Object {hi: ""} "object"

And even:

function Thing() { 
  this.a = 'a';
  return { hi: '' };
}
var t = new Thing();
console.log(t, typeof t); // => Object {hi: ""} "object"

So, why does a constructor function in JavaScript return an object, but not a primitive, if you write this kind of code?


This behaviour is also mentioned in this SO answer, but not explained. I've also scrolled over The new Operator part of the ECMAScript specification, and its Construct snipped, but this was not enlightening.

Any hints or knowledge (in plain English, please)?

解决方案

That's because, by definition, the purpose of constructors is producing objects, not primitives:

4.3.4 constructor

function object that creates and initialises objects

Therefore, the [[Construct]] internal method (called via the new operator), checks the type of the value returned by [[Call]]:

13.2.2 [[Construct]]

  1. Let result be the result of calling the [[Call]] internal property of F, providing obj as the this value and providing the argument list passed into [[Construct]] as args.
  2. If Type(result) is Object then return result.
  3. Return obj.

In fact, this is an invariant:

[[Construct]] ( )

  • The Type of the return value must be Object.

这篇关于为什么构造函数返回对象,而不是JavaScript中的原语?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆