我是JavaScript的面向对象编程(来自C++领域)的新手。调用构造函数的成员函数
我想知道从构造函数调用成员函数的最佳做法。
以下是一段代码: 很明显,“initialize”是在调用“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引擎不会首先读取对象的所有成员函数声明吗?
function Foo() {
this.initialize(); //failed here
this.initialize = function() {
alert("initialize");
};
this.hello = function() {
alert("helloWorld");
this.initialize();
};
};
var f = new Foo();
f.hello();
然后我做了这样的改变。
函数“初始化”在构造上执行,但函数“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.";
}
您必须在调用它之前定义函数,因此您的第二个代码将不起作用。此外,第三个(最后一个)将不起作用,因为**初始化**不是函数,因为你在末尾有'()',这是一个返回值 – Cilan