我认为可能需要强调的是,在 JavaScript 中,您需要定义对象的函数(或方法,如果您更喜欢该术语)在调用它们之前。
例如,如果您想在实例化时调用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 不是函数
这是我多年前在尝试了解如何在 JS 中进行 OOP 时遇到的一个问题。因为在 Java 或 PHP 等其他语言中,您通常在类的顶部有一个构造函数/方法,然后在您的其他函数/方法中编写下方。
因此,这样编写类似乎是合乎逻辑的:1) 定义对象的属性,然后 2) 列出实例化对象时要执行的操作,然后 3) 列出其他类函数/方法。
但是没有!!
使用 JavaScript,您必须在调用对象函数之前定义它们。
因此,如果您想在对象创建/实例化时调用两个方法,比如说this.func1() 和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!
}
如果你想让你的代码用构造方法组织在其他类方法的顶部(如前所述,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
}
有些人可能会说这有点多余,但是任何有助于加快您的工作流程的方法... :)
为了记录,如果你想在创建/实例化一个对象时传递一些参数,说你想有设置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
}