javascript 如何在Javascript中的对象构造期间调用函数?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/4791037/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to call a function during object construction in Javascript?
提问by Parminder
I want to create an object and run two of its methods on object creation. So if my object is
我想创建一个对象并在创建对象时运行它的两个方法。所以如果我的对象是
function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){...};
}
and the call to the object is
对对象的调用是
var temp = new newObj();
I want to run func1()and func2()without calling them explicity on temp variable, like temp.func1().  I want them to be called when I create the new Object variable. I tried putting this.func1()inside the newObjdeclaration but it doesn't seem to work. 
我想运行func1(),并func2()没有呼吁临时变量他们明确地一样temp.func1()。我希望在创建新的 Object 变量时调用它们。我试着把声明放在this.func1()里面,newObj但它似乎不起作用。
回答by Zango
Add method invocation statements in constructor:
在构造函数中添加方法调用语句:
function newObj(){
this.v1 = 10;
this.v2 = 20;
this.func1 = function(){ ....};
this.func2 = function(){...};
this.func1();
this.func2();
}
I think it is solution of your needs.
我认为这是您需求的解决方案。
回答by Shadow Wizard is Ear For You
Just call it from within the constructor itself it works just fine: http://jsfiddle.net/yahavbr/tTf9d/
只需从构造函数本身调用它它就可以正常工作:http: //jsfiddle.net/yahavbr/tTf9d/
The code is:
代码是:
function newObj(){
    this.v1 = 10;
    this.v2 = 20;
    this.func1 = function() { alert("func1"); };
    this.func2 = function() { alert("func2"); };
    this.func1();
    this.func2();
}
回答by Flavius Stef
This works for me in Chrome:
这在 Chrome 中对我有用:
function newObj(){
  this.v1 = 10;
  this.v2 = 20;
  this.func1 = function(){ this.v1 += 1; };
  this.func2 = function(){ alert(this.v1); };
  this.func1();
  this.func2();
}
var obj = new newObj();
回答by Moshe K.
Try wrapping it in an self invoking function if you never plan on reusing it, like this:
如果您从未打算重用它,请尝试将其包装在自调用函数中,如下所示:
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);
回答by Nishant Kumar
Using Self invoking function we can call and we can also share parent parameter by doing some work around public variable var that = this;
使用我们可以调用的自调用函数,我们还可以通过围绕公共变量做一些工作来共享父参数 var that = this;
function newObj(){
this.v1 = 10; // public variable
this.v2 = 20; // public variable
var that = this;  // Allow access to parent function variable to inner function
   (function(){
     // access parent function variable
     // using 'that' ex: 
       that.v1 = 50;
     //fun1code stuff 
   })();
   (function(){
     // access parent function variable
     // using 'that' ex: 
     that.v2 = 60;
     //fun2code stuff 
   })();
}
var temp = new newObj();
console.log(temp.v1);  // output 50
console.log(temp.v2);  // output 60
回答by dean.huczok
I think perhaps it needs to be stresed that in JavaScript you need to define the object's functions(or methods, if you prefer that term) before you call them.
我想也许它需要stresed是在JavaScript中,你需要定义对象的函数(或方法,如果你喜欢这个词)你叫他们面前。
For example, if you want to call this.func1()upon instantiation:
例如,如果您想调用this.func1()实例化:
var new_object = new newObj();  // create/instantiate an object
function newObj(){
  this.v1 = 10;
  this.v2 = 20;
  this.func1();  //  <-- calling it here causes an error
  this.func1 = function(){ ....};
  this.func2 = function(){ ....};
  this.func3 = function(){ ....};
}
TypeError: this.func1 is not a function
类型错误:this.func1 不是函数
This is a problem I came across years ago when trying to understand how to do OOP in JS. Because in other languages like Java or PHP, you have a constructor function/method usually at the top of your class, and beneath you write in your other functions/methods.
这是我几年前在尝试了解如何在 JS 中执行 OOP 时遇到的一个问题。因为在其他语言(如 Java 或 PHP)中,通常在类的顶部有一个构造函数/方法,在您编写其他函数/方法的下方。
So it would seem logical to write your class thus: 1) define your object's properties, and then 2) list the things you want to do when the object is instantiated, and then 3) list the other class functions/methods.
因此,这样编写类似乎是合乎逻辑的:1) 定义对象的属性,然后 2) 列出对象实例化时要执行的操作,然后 3) 列出其他类函数/方法。
BUT NO!!
但不是!!
With JavaScript, you must define the object's functions before you call them.
使用 JavaScript,您必须先定义对象的函数,然后再调用它们。
So if you want to call two methods on object creation/instantiation, lets say this.func1()and this.func2(), first define everything in your class and at the endplace your method calls:
因此,如果您想在对象创建/实例化时调用两个方法,比如说this.func1()and this.func2(),首先定义您的类中的所有内容,最后放置您的方法调用:
var new_object = new newObj();  // create/instantiate an object
function newObj(){
  this.v1 = 10;
  this.v2 = 20;
  this.func1 = function(){ ....};
  this.func2 = function(){ ....};
  this.func3 = function(){ ....};
  this.func1();  //  <-- it works here!
  this.func2();  //  <-- it works here!
}
If you wanted to have your code organised with a constructor method placed at the top of other class methods (like previously mentioned, how PHP and Java do it) then you could make a little this._constructor()method and place things there, and call it at the end of your class:
如果你想让你的代码组织一个构造器方法放在其他类方法的顶部(就像前面提到的,PHP 和 Java 是如何做到的)那么你可以创建一个小this._constructor()方法并将东西放在那里,并在最后调用它你的班级:
function newObj(){
  this.v1 = 10;
  this.v2 = 20;
  this._constructor = function(){  // do constructor things here
    this.func1();
    this.func2();
  }
  this.func1 = function(){ ....};
  this.func2 = function(){ ....};
  this.func3 = function(){ ....};
  this._constructor();  // call just one method here, nice and tidy
}
Some may say it's kinda redundant, but whatever helps to make your workflow faster... :)
有些人可能会说这有点多余,但任何有助于加快工作流程的方法...... :)
Just for the record, if you want to pass some argument when creating/instantiating an object, say you wanted to have the option to set this.v1then you could do it like this:
只是为了记录,如果你想在创建/实例化一个对象时传递一些参数,假设你想要设置选项,this.v1那么你可以这样做:
function newObj(set_v1){
  this.v1 = 10;
  this.v2 = 20;
  this._constructor = function(set_v1){  // do constructor things here
    if ( set_v1 != undefined ){  // you can come up with a better condition here
      this.v1 = set_v1;
    }
    this.func1();
    this.func2();
  }
  this.func1 = function(){ ....};
  this.func2 = function(){ ....};
  this.func3 = function(){ ....};
  this._constructor(set_v1);  // call the constructor here and pass the argument
}

