我是Java的面向对象编程的新手(来自C ++领域)。
我想知道从构造函数调用成员函数的最佳实践。
以下是一段有效的代码:
显然,“初始化”是在调用“ this.initialize();”之前声明的。
function Foo() {
this.initialize = function() {
alert("initialize");
};
this.hello = function() {
alert("helloWorld");
this.initialize();
};
this.initialize();
};
var f = new Foo();
f.hello();
如果我按以下方式更改代码,它将在“ this.initialize();”处失败。
问题1为什么会这样? Javascript Engine不会首先读取对象的所有成员函数声明吗?
function Foo() {
this.initialize(); //failed here
this.initialize = function() {
alert("initialize");
};
this.hello = function() {
alert("helloWorld");
this.initialize();
};
};
var f = new Foo();
f.hello();
然后我进行了这样的更改。
函数“ initialize”在构造时执行,但是在函数“ hello”中调用“ this.initialize()”失败。
function Foo() {
this.initialize = function() {
alert("initialize");
}();
this.hello = function() {
alert("helloWorld");
this.initialize(); //failed here
};
};
var f = new Foo();
f.hello();
问题2:第一段代码是从构造函数调用成员函数的唯一方法吗?
更新:
如果我必须在使用它之前定义一个函数,问题3:为什么下面的代码起作用?
function Foo() {
this.hello = function() {
alert("helloWorld");
this.initialize();
};
this.initialize();
};
Foo.prototype.initialize = function() {
alert("initialize");
};
var f = new Foo();
f.hello();
问题4:
为什么以下代码成功? (考虑“未来”功能是在调用后定义的)
alert("The future says: " + future());
function future() {
return "We STILL have no flying cars.";
}
最佳答案
从构造函数调用方法:
var f = new Foo();
function Foo() {
this.initialize(); //failed here
};
Foo.prototype.initialize = function() {
alert("initialize");
};
执行过程:
1) All functions are created (that are defined at the root)
2) Code is executed in order
3) When Foo is created/constructed it executes the code.
It try's to run Initialize() but it doesn't find it,
it throws an internal exception that is caught and
then creates the Prototype method and executes it.
4) If the Foo.Prototype.initialize line came BEFORE the,
"var f = new Foo()" then the initialize function would have existed.
此过程在每行执行中都会发生。
关于javascript - 从构造函数调用成员函数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/21011222/