如何在javascript中使用构造函数返回实例或其他内容?

如何在javascript中使用构造函数返回实例或其他内容?,javascript,constructor,Javascript,Constructor,我的班级定义: var Scregal = function(gallery, opts) { //some code }; var scregal=新scregal(“.gallery box”,选项) 如何在构造函数内返回与Scregal实例不同的东西?有可能吗?有可能从构造函数返回非隐式this的值。但是,只能返回对象,而不能返回基元值。原语返回值将被忽略,而原始的this将被返回 function A() { return 'test'; //primitive } ne

我的班级定义:

var Scregal = function(gallery, opts) {
    //some code
};
var scregal=新scregal(“.gallery box”,选项)


如何在构造函数内返回与Scregal实例不同的东西?有可能吗?

有可能从构造函数返回非隐式
this
的值。但是,只能返回对象,而不能返回基元值。原语返回值将被忽略,而原始的
this
将被返回

function A() {
  return 'test'; //primitive
}

new A() !== 'test';
new A() instanceof A; //return value ignored

function B() {
  return new String('test'); //wrapper type
}

new B() instanceof String;
new B() == 'test'; //strict equality (===) wouldn't work

可以从构造函数返回隐式
this
以外的值。但是,只能返回对象,而不能返回基元值。原语返回值将被忽略,而原始的
this
将被返回

function A() {
  return 'test'; //primitive
}

new A() !== 'test';
new A() instanceof A; //return value ignored

function B() {
  return new String('test'); //wrapper type
}

new B() instanceof String;
new B() == 'test'; //strict equality (===) wouldn't work

可以从构造函数返回隐式
this
以外的值。但是,只能返回对象,而不能返回基元值。原语返回值将被忽略,而原始的
this
将被返回

function A() {
  return 'test'; //primitive
}

new A() !== 'test';
new A() instanceof A; //return value ignored

function B() {
  return new String('test'); //wrapper type
}

new B() instanceof String;
new B() == 'test'; //strict equality (===) wouldn't work

可以从构造函数返回隐式
this
以外的值。但是,只能返回对象,而不能返回基元值。原语返回值将被忽略,而原始的
this
将被返回

function A() {
  return 'test'; //primitive
}

new A() !== 'test';
new A() instanceof A; //return value ignored

function B() {
  return new String('test'); //wrapper type
}

new B() instanceof String;
new B() == 'test'; //strict equality (===) wouldn't work

您可以从构造函数返回任何对象,该对象将被视为创建的值。(如果返回原语,将忽略它并返回实际创建的对象)

函数对象(类型){
如果(类型=“日期”){
返回新日期();
}else if(类型==“字符串”){
返回新字符串(“Hello!”);
}
}
控制台日志(新事物(“日期”);
log(新事物(“字符串”);

console.log(newthing())您可以从构造函数返回任何对象,该对象将被视为创建的值。(如果返回原语,将忽略它并返回实际创建的对象)

函数对象(类型){
如果(类型=“日期”){
返回新日期();
}else if(类型==“字符串”){
返回新字符串(“Hello!”);
}
}
控制台日志(新事物(“日期”);
log(新事物(“字符串”);

console.log(newthing())您可以从构造函数返回任何对象,该对象将被视为创建的值。(如果返回原语,将忽略它并返回实际创建的对象)

函数对象(类型){
如果(类型=“日期”){
返回新日期();
}else if(类型==“字符串”){
返回新字符串(“Hello!”);
}
}
控制台日志(新事物(“日期”);
log(新事物(“字符串”);

console.log(newthing())您可以从构造函数返回任何对象,该对象将被视为创建的值。(如果返回原语,将忽略它并返回实际创建的对象)

函数对象(类型){
如果(类型=“日期”){
返回新日期();
}else if(类型==“字符串”){
返回新字符串(“Hello!”);
}
}
控制台日志(新事物(“日期”);
log(新事物(“字符串”);

console.log(newthing())你为什么要这样做?这不是有点令人困惑吗?听起来你在寻找一种工厂模式。你为什么要这么做?这不是有点令人困惑吗?听起来你在寻找一种工厂模式。你为什么要这么做?这不是有点令人困惑吗?听起来你在寻找一种工厂模式。你为什么要这么做?这不是有点令人困惑吗?听起来你在寻找工厂模式。