当从另一个上下文中调用方法时,' this '未定义
`this` is undefined when calling method from another context
这是我第一次为JS创建OOP。我遵循了一些教程,但我无法理解这个问题。我知道这个问题,但我不知道解决办法。
function NewApp(name){
this.name = name;
this.currentPage = 1;
this.customObjectWithMethods = //init with options and so on
}
NewApp.prototype.logic = function(){
// Note 1.
var app = this
//Note 3.
this.customObjectWithMethods.method{
if(app.currentpage < 3)
// Note 2.
app.navigate(app.logic)
}
}
NewApp.prototype.navigate = function(sender){
var app = this;
this.customObjectWithMethods.method{
app.currentpage++;
this.method(function() {
return app.currentPage === 2;
}, sender(), this.terminate);
}
}
- 注1:我需要创建一个引用,因为在那之后,
this
没有 - 注2:检查后,我想在另一种方法中做一些逻辑并重复当前函数,但是当函数再次运行时,它会在方法(
this.customObjectWithMethods
)上中断,因为this
不存在。 - 注3:这是它中断的地方,因为"This"第一次工作而不是第二次。
this
-关键字变得非常复杂,这让我觉得我的设计可能有缺陷。
这个问题有解决方案吗,或者我应该重构它吗?
肯定会变得复杂,this
关键字并不总是指向主对象,而是指向使用它的作用域,请查看 scope和JavaScript中的这个以获取更多信息。
这是你的方法,创建一个包含构造函数的变量,并将这两个方法添加到该变量中,之后你可以调用你的函数:
var newApp = function newApp(name){
this.name = name;
this.currentPage = 1;
//Make a reference to your object here
var THIS = this;
this.logic = function(){
var sender = this;
THIS.customObjectWithMethods.method = function(){
if(THIS.currentpage < 3)
THIS.navigate(sender);
}
}
this.navigate = function(sender){
this.customObjectWithMethods.method = function(){
THIS.currentpage++;
this.method(function() {
return THIS.currentPage === 2;
}, sender(), this.terminate);
}
}
}
下面是如何使用构造函数和它的方法:
var app = newApp("Test");
//Call the first method
app.customObjectWithMethods();
//Thenn call the second one
app.logic();
部分语法错误&风格问题——这是一个简短的更正
var myFunction = function(){
//code here
};
var mySecondFunction = function(){
//code here
};
function NewApp(name){
this.name = name;
this.currentPage = 1;
this.customObjectWithMethods = function(){}; //empty function so calling doesnt resolve in error
}
NewApp.prototype.logic = function(){
this.customObjectWithMethods.method = mySecondFunction.bind(this);
}
NewApp.prototype.navigate = function(sender){
this.customObjectWithMethods.method = myFunction.bind(this);
}
我已经将这两个函数移到了构造函数之外,这样它们就不会在每次调用构造函数时都被重新创建。
与_.bind(this)"this"引用被传递到你的函数的范围(我认为这比创建另一个var更漂亮)。
var reff = new NewApp('namename');
你现在可以开始调用你的函数了:
ref.logic();
也许这个方法对你有用?
相关文章:
- this.router在AngularJS 2中未定义
- React+Meteor:this.ops返回未定义
- `当使用箭头函数时,“开发工具”中未定义“this”
- jQuery$(this)引用未定义
- this.defaultValue 返回 select 元素的未定义
- Alt flux action:_this.actions未定义,即使调用了this.generateActions
- $(this).attr({class:“activeTab”});不起作用,因为这是未定义的
- $(this)抛出“;未定义的“;但这是按预期进行的
- jqueryui:"类型错误:this.menu.element未定义"
- this.value在<td>标记显示未定义
- $(this)返回'未定义'
- TypeError:this.clusterer在Rails模型名称更改后未定义
- this._id流星中未定义
- Angular ES6,THIS,Scope和EL在JQLITE点击事件中全部未定义
- this.userId 在 Meteor.publish 中返回未定义
- 为什么我需要将“var value = val;”更改为“this.value = val;”,这样我就不会收到“未定义
- ReactJS - {this.props.children} 是未定义的
- 为什么 this.name 未定义
- `expressJS路由处理程序中未定义this
- 在Route类中未定义this.controller