从另一个Javascript内部调用一个函数的属性
我使用函数作为类的表示从另一个Javascript内部调用一个函数的属性,javascript,Javascript,我使用函数作为类的表示 function ClassOne() { this.doFunc = function() { console.log("doFunc output"); } } function ClassTwo() { this.one = ClassOne(); console.log(this.one); // == undefined ??? this.init = function() { this.one.doFunc(); }
function ClassOne()
{
this.doFunc = function() {
console.log("doFunc output");
}
}
function ClassTwo()
{
this.one = ClassOne();
console.log(this.one); // == undefined ???
this.init = function() {
this.one.doFunc();
}
this,init();
}
ClassTwo();
但我正努力在一个函数中使用另一个函数
例如,上述代码返回“无法读取未定义的属性'doFunc'”
为什么this.one==未定义?如果在函数中指定this的属性,通常表示该函数将作为具有
new
的构造函数调用,例如:
this.one = new ClassOne();
否则,如果函数不返回任何内容。。。然后,什么也不会返回(=>未定义的(
)
函数ClassOne()
{
this.doFunc=函数(){
log(“doFunc输出”);
}
}
函数class2()
{
this.one=新的ClassOne();
console.log(this.one);
this.init=函数(){
this.one.doFunc();
}
this.init();
}
第二类()
为什么this.one==未定义?:因为您正在执行函数,而函数没有return
语句。因此,它返回undefined
并将其分配给您的this.one
属性。您需要使用new ClassOne()
才能让它为您创建一个实例。