简体   繁体   English

如何从构造函数内部返回构造函数的对象

[英]How to return object of constructor from inside the constructor

How can I return the object from constructor from inside the constructor? 如何从构造函数内部从构造函数返回对象?

  function consFunc() { this.flag = 'someFlag'; this.pol = 'somePole'; } consFunc.prototype.foo = function(){ console.log(this.flag); } var obj = new consFunc(); obj.foo(); 

This is how usually I make object from constructor. 这通常是我从构造函数制作对象的方式。 How can I return object from inside the constructor function so I no need to write var obj = new consFunc(); 我怎么能从构造函数内部返回对象,所以我不需要写var obj = new consFunc(); I just simply call obj.foo(); 我只是简单地调用obj.foo(); for my need, is it possible? 我需要,有可能吗?

If you want to have an object with a simple function on it you can simply write 如果您想要一个带有简单功能的对象,则只需编写

var consObj = {
  flag: 'someFlag',
  pol: 'somePole',       
  foo: function() { console.log( this.flag ); }
}

consObj.foo() // 'someFlag'

You could wrap your constructor in another function and return new consFunc(); 您可以将构造函数包装在另一个函数中,并返回new consFunc(); from that function: 从该功能:

 function obj() { function consFunc() { this.flag = 'someFlag'; this.pol = 'somePole'; } consFunc.prototype.foo = function () { console.log(this.flag); } return new consFunc(); } // now use it obj().foo() 

If you need some sort of singleton: 如果您需要某种单例:

var obj = (function (){

    var flag = 'someFlag';
    var pol = 'somePole';   

    function foo(){      
        console.log(flag);
    }

    return {
      foo: foo
    };
})();

obj.foo();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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