对象的构造函数或init函数

emp*_*ine 16 javascript oop

我正在寻找以下情况的构造函数或init函数:

var Abc = function(aProperty,bProperty){
   this.aProperty = aProperty;
   this.bProperty = bProperty;
}; 
Abc.prototype.init = function(){
   // Perform some operation
};

//Creating a new Abc object using Constructor.

var currentAbc = new Abc(obj,obj);

//currently I write this statement:
currentAbc.init();
Run Code Online (Sandbox Code Playgroud)

新对象初始化时有没有办法调用init函数?

Mat*_*eer 21

你可以init()从构造函数调用

var Abc = function(aProperty,bProperty){
   this.aProperty = aProperty;
   this.bProperty = bProperty;
   this.init();
}; 
Run Code Online (Sandbox Code Playgroud)

这是一个小提示演示:http://jsfiddle.net/CHvFk/

  • 我在这种模式中看到的缺点是init是公共的.它可以像a.init()一样调用.Usualy init函数是私有的.因此,在构造函数中定义它可能是好的.见[小提琴更新](http://jsfiddle.net/CHvFk/126/) (4认同)

Jam*_*Hay 12

也许是这样的?

var Abc = function(aProperty,bProperty){
    this.aProperty = aProperty;
    this.bProperty = bProperty;
    this.init = function(){
        // Do things here.
    }
    this.init();
}; 
var currentAbc = new Abc(obj,obj);
Run Code Online (Sandbox Code Playgroud)

  • 这是正确的,您必须在定义后调用init()函数. (2认同)

Fle*_*ing 5

如果你的init方法应该保密:

var Abc = function(aProperty,bProperty){
   function privateInit(){ console.log(this.aProperty);}   
   this.aProperty = aProperty;
   this.bProperty = bProperty;

   privateInit.apply(this);
};
Run Code Online (Sandbox Code Playgroud)

我更喜欢这个.