javascript匿名对象的构造函数

时间:2014-01-29 00:28:20

标签: javascript node.js sails.js

从PHP迁移到NodeJS(JavaScript)后,我遇到了JavaScript的匿名对​​象的问题 - 我无法弄清楚如何创建一个匿名对象的构造函数,就像在PHP中使用__construct()一样函数或Python的__init__(self)函数。也许像Java [Link] JavaScript不能拥有匿名构造函数......

解决方案:

在阅读了评论和其他答案后,我发现通过使用返回对象的匿名函数可以获得此功能:

var a = new function() {
  var constTxt = [not constructed]';

  /* emulating a constructor */
  if (true) {
     constTxt = '[constructed]';
  }

  return {
    functionABC : function() {
      return 'abc ' +  constTxt;
    },
    functionDCF : function() {
      return 'other function';
    }
  };
}; 

2 个答案:

答案 0 :(得分:1)

您将其声明为函数,并且当您使用new module.exports()实例化该函数时,该函数将成为构造函数。然后这些方法继续使用函数原型:

module.exports = function(arg) {...};

module.exports.prototype = {
    functionABC: function() {return 'abc'},
    functionDEF: function() {return 'def'}
}

var myExports = new module.exports();

myExports.functionABC("hello");

我不确定您对问题的anonymous部分提出了什么要求。对象的名称是构造函数,因此这里没有匿名对象。


或者,如果你想要一个从构造函数调用的方法,你可以这样做:

module.exports = function(arg) {
    // put whatever code you want in the constructor
    if (arg) {
        this.functionABC();
    } else {
        this.functionDEF();
    }
};

module.exports.prototype = {
    functionABC: function() {return 'abc'},
    functionDEF: function() {console.log('def');}
}

var myExports = new module.exports(true);   // will execute the constructor

答案 1 :(得分:1)

我真的不知道你想做什么但是在javascript中任何函数都可以用作构造函数。 函数是构造函数的事实取决于调用函数的方式,如果在函数之前调用“new”,函数将表现为构造函数。

另外,要小心“this”,它指的是函数的一个对象(或严格模式下的任何值),并且是通过函数的调用方式来设置的或使用 bind 。如果函数作为构造函数调用,则它是新创建的对象,但仅在该情况下