构造函数返回函数或对象的JavaScript类有什么问题 [英] What's wrong with a JavaScript class whose constructor returns a function or an object

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

问题描述

当我使用 new 来实现某个类的实例时,我得到了实际的实例。当构造函数具有返回值时, new 语句也会给出实际实例。但是,当构造函数返回自身时,我无法获取实例。相反,我得到了构造函数。我想知道这有什么问题。

When I use new to instainciate an instance of a certain class, I got the actual instance. When the constructor function has a return value, the new sentence gives out the actual instance also. However, when the constructor returns itself, I can't get the instance. Instead I get the constructor. I wander what's wrong with this.

这是我的测试代码片段:

Here are my test code fragment:

function foo() {
    this.x = 1;
    return foo;
}
console.log(new foo()); // prints the defination of foo






我们考虑在大多数情况下,它不会返回这样的函数。但是,为什么JS有这样的功能呢?在设计JS时有什么考虑吗?或者它只是JS的一个错误?


As we consider, in most situations, it makes no sence to return a function like this. However, why does JS has such a feature? Is there any consideration when designing JS? Or is it just a bug of JS?

推荐答案

如果从构造函数返回一个对象,那么<$ c的结果$ c> new ... 表达式将是您返回的对象:

If you return an object from a constructor, the result of the new ... expression will be the object you returned:

function myWackyConstructor() {
  return new Date();
}

var d = new myWackyConstructor();
console.log(d);

如果返回原语,结果将是构造的对象:

If you return a primitive, the result will be the constructed object:

function myWackyConstructor() {
  this.gotAValue = true;

  return 3;
}

var v = new myWackyConstructor();
console.log(v.gotAValue);

通常,您不应该从构造函数返回任何内容:

Typically, you should not return anything from a constructor:

function myNormalConstructor() {
  this.gotAValue = true;
}

var v = new myNormalConstructor();
console.log(v.gotAValue);

问题是,为什么你从它自己返回构造函数?

The question is, why are you returning the constructor from itself?

这篇关于构造函数返回函数或对象的JavaScript类有什么问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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