如何在Javascript中的对象构造期间调用函数?

Par*_*der 11 javascript function object call

我想创建一个对象,并在对象创建时运行它的两个方法.所以,如果我的对象是

function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){...};
}
Run Code Online (Sandbox Code Playgroud)

并且对该对象的调用是

var temp = new newObj();
Run Code Online (Sandbox Code Playgroud)

我想运行func1()并且func2()不要在temp变量上明确表示它们,例如temp.func1().我希望在创建新的Object变量时调用它们.我试图把this.func1()里面newObj的声明,但它似乎并没有工作.

Zan*_*ngo 10

在构造函数中添加方法调用语句:

function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){...};
this.func1();
this.func2();
}

我认为这是您需求的解决方案.


Sha*_*ard 6

只需从构造函数本身调用它就可以正常工作:http://jsfiddle.net/yahavbr/tTf9d/

代码是:

function newObj(){
    this.v1 = 10;
    this.v2 = 20;
    this.func1 = function() { alert("func1"); };
    this.func2 = function() { alert("func2"); };

    this.func1();
    this.func2();
}
Run Code Online (Sandbox Code Playgroud)


Mos*_* K. 1

如果您从不打算重用它,请尝试将其包装在自调用函数中,如下所示:

function newObj(){
    this.v1 = 10;
    this.v2 = 20;
    this.func1val = (function(){ alert('called from c\'tor'); })();
    this.func2val = (function(){ return 2 + 1; })();
}

var temp = new newObj();
alert('temp.func2val = ' + temp.func2val);
Run Code Online (Sandbox Code Playgroud)

演示版