gpt4 book ai didi

javascript - 丢失对父类的引用

转载 作者:行者123 更新时间:2023-11-28 13:36:44 25 4
gpt4 key购买 nike

我有两个 TypeScript 类;其中一个有一个方法,该方法返回对第二个类的实例中的不同方法的引用(是的,有点令人困惑)。这是一个最淡化的例子,仍然重现了这个问题(我在底部包含了编译后的 JS):

class OuterClass {
public InnerClassInstance: InnerClass;

constructor() {
this.InnerClassInstance = new InnerClass(7); //Create an instance of the inner class
//7 is just a test value
}

public DoStuff(): any { //Return a reference to the instance's method
return this.InnerClassInstance.DoMoreStuff;
}
}

class InnerClass {
public VariableInstance: number; //Keep a variable (this is the main issue)

constructor(Num: number) {
this.VariableInstance = Num;
}

public DoMoreStuff() {
alert(this.VariableInstance); //Demonstrate (hopefully) that everything worked
//Displays 'undefined' instead
}
}

var OuterClassInstance: OuterClass = new OuterClass();
OuterClassInstance.DoStuff()(); //Call DoMoreStuff from the instance in OuterClass

问题是,一旦调用 DoMoreStuff,它似乎就失去了与其父类的所有连接。此时,实例 InnerClassInstance 仍然正确(变量为 7),但直接从 DoMoreStuff 访问时 VariableInstance 未定义。 InnerClass 中定义的所有变量都会发生这种情况。

是否有某种我错过的规范?我认为引用会保留它的上下文,但当从引用调用它时,它似乎会丢失它的上下文。

这是 JS:

var OuterClass = (function () {
function OuterClass() {
this.InnerClassInstance = new InnerClass(7); //Create an instance of the inner class
//7 is just a test value
}
OuterClass.prototype.DoStuff = function () {
return this.InnerClassInstance.DoMoreStuff;
};
return OuterClass;
})();

var InnerClass = (function () {
function InnerClass(Num) {
this.VariableInstance = Num;
}
InnerClass.prototype.DoMoreStuff = function () {
alert(this.VariableInstance); //Demonstrate (hopefully) that everything worked
//Displays 'undefined' instead
};
return InnerClass;
})();

var OuterClassInstance = new OuterClass();
OuterClassInstance.DoStuff()(); //Call DoMoreStuff from the instance in OuterClass

最佳答案

DoMoreStuff 被直接调用(即不作为方法调用),因此 this 获取 window 全局对象的值。

DoMoreStuff 正在尝试获取 window.VariableInstance,它确实未定义。

要使其工作,您需要的内容如下:

var InnerClass = (function () {
var _this = this; // <--- closure for class instance
function InnerClass(Num) {
this.VariableInstance = Num;
}
InnerClass.prototype.DoMoreStuff = function () {
alert(_this.VariableInstance); // <--- using class instance
};
return InnerClass;
}

阅读其他响应后,看来bind()是解决方案。问题是,它仅受 ECMA5 浏览器支持,因此旧的 IE 版本不会有它。

bind() 的可能替代品是:

function bind (proc, _this) {
if (proc.prototype.bind) return proc.bind (_this);
return function () { proc.call (_this); };
}

关于javascript - 丢失对父类的引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20876274/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com